// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using UnityEditor;
using UnityEngine;
using Theme = WPFMA.Editor.WPFMAProjectKindWindow;

namespace WPFMA
{
    [InitializeOnLoad]
    internal static class WPFMAWelcomeBootstrap
    {
        static WPFMAWelcomeBootstrap()
        {
            EditorApplication.delayCall += TryShowWelcome;
        }

        private static void TryShowWelcome()
        {
            if (!WPFMAWelcomeSettings.ShouldAutoShow)
                return;

            WPFMAWelcomeSettings.MarkShown();
            WPFMAWelcomeWindow.OpenFromStartup();
        }
    }

    internal static class WPFMAWelcomeSettings
    {
        private const string ShowOnFreshInstallPrefKey = "WPFMA.Welcome.ShowOnFreshInstall";
        private const string HasShownPrefKey = "WPFMA.Welcome.HasShown";

        private static string ProjectScopedSuffix
        {
            get
            {
                var projectPath = System.IO.Path.GetDirectoryName(Application.dataPath) ?? "unknown-project";
                return "|" + projectPath.Replace('\\', '/').ToLowerInvariant();
            }
        }

        private static string KeyForProject(string baseKey)
        {
            return baseKey + ProjectScopedSuffix;
        }

        internal static bool ShowOnFreshInstall => EditorPrefs.GetBool(KeyForProject(ShowOnFreshInstallPrefKey), true);
        internal static bool HasShown => EditorPrefs.GetBool(KeyForProject(HasShownPrefKey), false);
        internal static bool ShouldAutoShow => ShowOnFreshInstall && !HasShown;

        internal static void SetShowOnFreshInstall(bool value)
        {
            EditorPrefs.SetBool(KeyForProject(ShowOnFreshInstallPrefKey), value);
        }

        internal static void MarkShown()
        {
            EditorPrefs.SetBool(KeyForProject(HasShownPrefKey), true);
        }
    }

    internal sealed class WPFMAWelcomeWindow : EditorWindow
    {
        private const string WindowTitle = "WPFMA-SDK Welcome";
        private const string VersionLabel = "BETA 1.17.1";

        private static readonly Vector2 WindowSize = new Vector2(560f, 432f);

        private struct Card
        {
            public string Title;
            public string Body;
            public WPFMAWindow.Tab Tab;
        }

        private static readonly Card[] Cards =
        {
            new Card
            {
                Title = "Exporter",
                Body = "Drop in .vrca, .vrcw or .vrcb files. Peek inside, preview them, and export to a prefab.",
                Tab = WPFMAWindow.Tab.Ripper
            },
            new Card
            {
                Title = "Tools",
                Body = "Modular Avatar, Avatar Compressor, toggle creator, FBX export and re-upload.",
                Tab = WPFMAWindow.Tab.Tools
            },
            new Card
            {
                Title = "Importer",
                Body = "Queue up .unitypackages to import in one go, and add VPM repos.",
                Tab = WPFMAWindow.Tab.Importer
            },
            new Card
            {
                Title = "Settings",
                Body = "Shader archive, animator defaults, hierarchy icons, Linux and more.",
                Tab = WPFMAWindow.Tab.Settings
            }
        };

        [NonSerialized] private GUIStyle titleStyle;
        [NonSerialized] private GUIStyle bodyStyle;
        [NonSerialized] private GUIStyle sectionStyle;
        [NonSerialized] private GUIStyle pillStyle;
        [NonSerialized] private GUIStyle cardTitleStyle;
        [NonSerialized] private GUIStyle cardBodyStyle;
        [NonSerialized] private GUIStyle cardOpenStyle;
        [NonSerialized] private GUIStyle footerStyle;
        [NonSerialized] private GUIStyle buttonStyle;

        internal static void OpenFromStartup()
        {
            var window = CreateInstance<WPFMAWelcomeWindow>();
            Prepare(window);
            window.ShowUtility();
            window.Focus();
        }

        internal static void OpenFromMenu()
        {
            var window = GetWindow<WPFMAWelcomeWindow>(true, WindowTitle, true);
            Prepare(window);
            window.Show();
        }

        private static void Prepare(WPFMAWelcomeWindow window)
        {
            window.titleContent = new GUIContent(WindowTitle);
            window.minSize = WindowSize;
            window.maxSize = WindowSize;
            window.wantsMouseMove = true;

            var main = EditorGUIUtility.GetMainWindowPosition();
            window.position = new Rect(
                main.x + (main.width - WindowSize.x) * 0.5f,
                main.y + (main.height - WindowSize.y) * 0.5f,
                WindowSize.x, WindowSize.y);
        }

        private void OnEnable()
        {
            wantsMouseMove = true;
        }

        private void OnGUI()
        {
            EnsureStyles();

            var e = Event.current;
            if (e.type == EventType.MouseMove)
                Repaint();

            float width = position.width;
            EditorGUI.DrawRect(new Rect(0f, 0f, width, position.height), Theme.Background);
            EditorGUI.DrawRect(new Rect(0f, 0f, width, 3f), Theme.Accent);

            GUI.Label(new Rect(28f, 22f, width - 56f - 100f, 30f), "Welcome to WPFMA-SDK", titleStyle);

            var pill = new Rect(width - 28f - 86f, 28f, 86f, 22f);
            EditorGUI.DrawRect(pill, Theme.AccentDim);
            GUI.Label(pill, VersionLabel, pillStyle);

            GUI.Label(new Rect(28f, 56f, width - 56f, 36f),
                "Who Pays For Models Anyways. Rip, fix and re-upload VRChat avatars, all from one panel.",
                bodyStyle);

            GUI.Label(new Rect(28f, 100f, width - 56f, 18f), "WHERE TO START", sectionStyle);

            const float top = 122f;
            const float gap = 12f;
            const float cardHeight = 92f;
            float cardWidth = (width - 56f - gap) * 0.5f;

            // The Exporter card goes when Settings hides the Exporter tab.
            var cards = System.Array.FindAll(Cards, c => c.Tab != WPFMAWindow.Tab.Ripper || !WPFMAWindow.ExporterHidden);
            for (int i = 0; i < cards.Length; i++)
            {
                float x = 28f + (i % 2) * (cardWidth + gap);
                float y = top + (i / 2) * (cardHeight + gap);
                if (DrawCard(new Rect(x, y, cardWidth, cardHeight), cards[i]))
                {
                    var tab = cards[i].Tab;
                    EditorApplication.delayCall += () => WPFMAWindow.OpenAt(tab);
                    Close();
                    GUIUtility.ExitGUI();
                }
            }

            float footer = top + 2f * cardHeight + gap + 16f;
            GUI.Label(new Rect(28f, footer, width - 56f, 18f),
                "Made by Literal   ·   Got an idea or found a bug? DM literal.",
                footerStyle);

            float bottom = footer + 38f;
            DrawShowToggle(new Rect(28f, bottom + 7f, 260f, 18f));

            var open = new Rect(width - 28f - 160f, bottom, 160f, 32f);
            var close = new Rect(open.x - 10f - 90f, bottom, 90f, 32f);

            if (DrawButton(open, "Open WPFMA-SDK", true))
            {
                EditorApplication.delayCall += WPFMAWindow.Open;
                Close();
                GUIUtility.ExitGUI();
            }

            if (DrawButton(close, "Close", false))
            {
                Close();
                GUIUtility.ExitGUI();
            }
        }

        private bool DrawCard(Rect rect, Card card)
        {
            bool hover = rect.Contains(Event.current.mousePosition);

            EditorGUI.DrawRect(rect, hover ? Theme.Accent : Theme.Border);
            var inner = new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f);
            EditorGUI.DrawRect(inner, hover ? Theme.PanelHover : Theme.Panel);
            EditorGUI.DrawRect(new Rect(inner.x, inner.y, 3f, inner.height), hover ? Theme.Accent : Theme.AccentDim);

            GUI.Label(new Rect(inner.x + 16f, inner.y + 10f, inner.width - 90f, 24f), card.Title, cardTitleStyle);
            if (hover)
                GUI.Label(new Rect(inner.xMax - 76f, inner.y + 12f, 64f, 20f), "Open →", cardOpenStyle);

            GUI.Label(new Rect(inner.x + 16f, inner.y + 36f, inner.width - 30f, inner.height - 42f), card.Body,
                cardBodyStyle);

            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            return Clicked(rect);
        }

        private void DrawShowToggle(Rect rect)
        {
            bool current = WPFMAWelcomeSettings.ShowOnFreshInstall;
            var box = new Rect(rect.x, rect.y + 1f, 16f, 16f);
            var label = new Rect(rect.x + 22f, rect.y, rect.width - 22f, rect.height);

            bool edited = EditorGUI.Toggle(box, current);
            GUI.Label(label, "Show this on fresh installs", footerStyle);
            EditorGUIUtility.AddCursorRect(label, MouseCursor.Link);

            if (Clicked(label))
                edited = !current;

            if (edited != current)
                WPFMAWelcomeSettings.SetShowOnFreshInstall(edited);
        }

        private bool DrawButton(Rect rect, string label, bool primary)
        {
            bool hover = rect.Contains(Event.current.mousePosition);

            if (primary)
            {
                EditorGUI.DrawRect(rect, hover ? Theme.Accent : Theme.AccentDim);
                buttonStyle.normal.textColor = hover ? Theme.AccentText : Theme.TitleText;
            }
            else
            {
                EditorGUI.DrawRect(rect, hover ? Theme.AccentDim : Theme.Border);
                EditorGUI.DrawRect(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f),
                    hover ? Theme.PanelHover : Theme.Background);
                buttonStyle.normal.textColor = Theme.BodyText;
            }

            GUI.Label(rect, label, buttonStyle);
            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            return Clicked(rect);
        }

        private static bool Clicked(Rect rect)
        {
            var e = Event.current;
            if (e.type != EventType.MouseDown || e.button != 0 || !rect.Contains(e.mousePosition))
                return false;

            e.Use();
            return true;
        }

        private void EnsureStyles()
        {
            if (titleStyle != null)
                return;

            titleStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 20,
                normal = { textColor = Theme.TitleText }
            };

            bodyStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 12,
                wordWrap = true,
                normal = { textColor = Theme.BodyText }
            };

            sectionStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 10,
                normal = { textColor = Theme.DimText }
            };

            pillStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 11,
                alignment = TextAnchor.MiddleCenter,
                normal = { textColor = Theme.Accent }
            };

            cardTitleStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 15,
                normal = { textColor = Theme.Accent }
            };

            cardBodyStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 11,
                wordWrap = true,
                alignment = TextAnchor.UpperLeft,
                normal = { textColor = Theme.BodyText }
            };

            cardOpenStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 11,
                alignment = TextAnchor.MiddleRight,
                normal = { textColor = Theme.Accent }
            };

            footerStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 11,
                normal = { textColor = Theme.DimText }
            };

            buttonStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 12,
                alignment = TextAnchor.MiddleCenter
            };
        }
    }
}
#endif
