#region Copyright

/* -----------------------------------------------------------------------------
 *  Copyright © 2024 • Chomp Studios • All Rights Reserved
 * -----------------------------------------------------------------------------
 *  Date: 21/11/2026
 *  -----------------------------------------------------------------------------
 *  Description: Shared colours, styles and drawing helpers for the tool
 *  windows, in the Chomp Games look: charcoal, cream and lime, using Unity's
 *  own editor font.
 *
 *  The dark editor skin gets the charcoal theme and the light skin gets the
 *  cream theme. The header band stays charcoal in both, as in the brand.
 *  -----------------------------------------------------------------------------
 */

#endregion

#if UNITY_EDITOR

#region Imports

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
#if UNITY_6000_5_OR_NEWER
using Unity.Scripting.LifecycleManagement;
#endif

#endregion

namespace Workflow_Toolkit.Utilities {
    public static class WorkflowStyles {
        #region Colours

        // Brand colours (Chomp Games design system)
        [NoAutoStaticsCleanup]
        public static readonly Color Charcoal = new Color32(32, 33, 35, 255);
        [NoAutoStaticsCleanup]
        public static readonly Color Cream = new Color32(255, 246, 217, 255);
        [NoAutoStaticsCleanup]
        public static readonly Color Lime = new Color32(205, 251, 39, 255);

        // Accent fills; change these to re-theme every tool
        [NoAutoStaticsCleanup]
        public static readonly Color Accent = Lime;
        [NoAutoStaticsCleanup]
        public static readonly Color AccentHover = new Color32(218, 255, 85, 255);
        [NoAutoStaticsCleanup]
        public static readonly Color AccentPressed = new Color32(181, 224, 26, 255);
        [NoAutoStaticsCleanup]
        public static readonly Color OnAccent = Charcoal;
        [NoAutoStaticsCleanup]
        public static readonly Color Danger = new Color32(255, 107, 94, 255);
        [NoAutoStaticsCleanup]
        public static readonly Color DangerHover = new Color32(255, 136, 126, 255);
        [NoAutoStaticsCleanup]
        public static readonly Color Warning = new Color32(255, 181, 71, 255);
        [NoAutoStaticsCleanup]
        public static readonly Color Success = new Color32(79, 216, 138, 255);

        private static bool Pro => EditorGUIUtility.isProSkin;

        public static Color WindowBackground => Pro ? Charcoal : Cream;
        public static Color HeaderBackground => Pro ? new Color32(24, 25, 27, 255) : Charcoal;
        public static Color CardBackground => Pro ? new Color32(42, 43, 46, 255) : new Color32(255, 251, 236, 255);
        public static Color CardBorder => Pro ? new Color32(74, 75, 80, 255) : new Color32(185, 174, 140, 255);
        public static Color StrongBorder => Pro ? new Color32(122, 123, 130, 255) : new Color32(133, 124, 98, 255);
        public static Color InsetBackground => Pro ? new Color32(32, 33, 35, 255) : new Color32(247, 237, 204, 255);
        public static Color Divider => Pro ? new Color32(58, 59, 64, 255) : new Color32(217, 207, 174, 255);
        public static Color HoverOverlay => Pro ? new Color(1f, 1f, 1f, 0.06f) : new Color(0f, 0f, 0f, 0.05f);
        public static Color Shadow => Pro ? new Color(0f, 0f, 0f, 0.35f) : new Color(0.32f, 0.27f, 0.12f, 0.16f);
        public static Color Text => Pro ? Cream : Charcoal;
        public static Color MutedText => Pro ? new Color32(184, 178, 160, 255) : new Color32(92, 90, 82, 255);
        public static Color AccentText => Pro ? Lime : new Color32(74, 95, 0, 255);
        public static Color DangerText => Pro ? Danger : new Color32(180, 35, 24, 255);
        public static Color WarningText => Pro ? Warning : new Color32(138, 81, 0, 255);
        public static Color DangerFill => Pro ? Danger : new Color32(180, 35, 24, 255);
        public static Color DangerFillHover => Pro ? DangerHover : new Color32(201, 52, 40, 255);
        public static Color OnDanger => Pro ? Charcoal : Color.white;
        public static Color InfoText => Pro ? new Color32(124, 200, 255, 255) : new Color32(29, 111, 165, 255);

        #endregion

        #region Text

        /// <summary>Upper-cases a label the way the brand shows them (works for every supported language).</summary>
        public static string Caps(string text) {
            return string.IsNullOrEmpty(text) ? text : text.ToUpperInvariant();
        }

        #endregion

        #region Styles

        // Editor-only UI cache that rebuilds itself whenever the editor skin changes, so keeping it between Play mode
        // sessions is harmless (hence [NoAutoStaticsCleanup], as Unity recommends for cached GUIStyles).
        [NoAutoStaticsCleanup]
        private static readonly StyleCache Cache = new();

        public static GUIStyle Title => Styles.Title;
        public static GUIStyle Description => Styles.Description;
        public static GUIStyle HeaderEyebrow => Styles.HeaderEyebrow;
        public static GUIStyle HeaderTitle => Styles.HeaderTitle;
        public static GUIStyle HeaderDescription => Styles.HeaderDescription;
        public static GUIStyle SectionTitle => Styles.SectionTitle;
        public static GUIStyle Badge => Styles.Badge;
        public static GUIStyle Caption => Styles.Caption;
        public static GUIStyle Footer => Styles.Footer;
        public static GUIStyle PrimaryButtonLabel => Styles.PrimaryButtonLabel;
        public static GUIStyle SmallButtonLabel => Styles.SmallButtonLabel;
        public static GUIStyle IconButton => Styles.IconButton;
        public static GUIStyle Placeholder => Styles.Placeholder;
        public static GUIStyle TitleField => Styles.TitleField;
        public static GUIStyle PathLabel => Styles.PathLabel;
        public static GUIStyle WrappedTextArea => Styles.WrappedTextArea;
        public static GUIStyle Card => Styles.Card;
        public static GUIStyle Inset => Styles.Inset;
        public static GUIStyle SubSection => Styles.SubSection;
        public static GUIStyle SubSectionTitle => Styles.SubSectionTitle;
        public static GUIStyle GroupLabel => Styles.GroupLabel;
        public static GUIStyle Callout => Styles.Callout;
        public static GUIStyle CalloutText => Styles.CalloutText;
        public static GUIStyle StatValue => Styles.StatValue;
        public static GUIStyle SecondaryButtonLabel => Styles.SecondaryButtonLabel;
        public static GUIStyle SidebarItem => Styles.SidebarItem;
        public static GUIStyle SidebarItemSelected => Styles.SidebarItemSelected;
        public static GUIStyle ChartLabel => Styles.ChartLabel;
        public static GUIStyle ChartValue => Styles.ChartValue;
        public static GUIStyle ChangeText => Styles.ChangeText;
        public static GUIStyle Tag => Styles.Tag;

        /// <summary>
        ///     The toolkit logo, loaded once from Resources.
        /// </summary>
        public static Texture2D Logo {
            get {
                if (Cache.Logo == null) Cache.Logo = Resources.Load<Texture2D>("workflow-logo");
                return Cache.Logo;
            }
        }

        /// <summary>
        ///     A soft white streak (transparent at both ends), used for the light sweeping across buttons.
        /// </summary>
        public static Texture2D Streak {
            get {
                if (Cache.Streak != null) return Cache.Streak;

                var texture = new Texture2D(64, 1, TextureFormat.RGBA32, false) {
                    hideFlags = HideFlags.HideAndDontSave, wrapMode = TextureWrapMode.Clamp
                };
                for (var x = 0; x < 64; x++) {
                    var a = Mathf.Sin(x / 63f * Mathf.PI);
                    texture.SetPixel(x, 0, new Color(1f, 1f, 1f, a * a));
                }

                texture.Apply();
                Cache.Streak = texture;
                return texture;
            }
        }

        // Styles depend on EditorStyles, so they are built lazily from inside OnGUI and rebuilt on skin change
        private static StyleSet Styles {
            get {
                if (Cache.Styles == null || Cache.Styles.BuiltForPro != Pro) Cache.Styles = new StyleSet(Pro);
                return Cache.Styles;
            }
        }

        private sealed class StyleCache {
            public Texture2D Logo, Streak;
            public StyleSet Styles;
        }

        private sealed class StyleSet {
            public readonly bool BuiltForPro;
            public readonly GUIStyle Card, Inset, SubSection, SubSectionTitle, GroupLabel, Callout, CalloutText;
            public readonly GUIStyle ChartLabel, ChartValue, ChangeText, Tag;
            public readonly GUIStyle HeaderEyebrow, HeaderTitle, HeaderDescription;

            public readonly GUIStyle PrimaryButtonLabel,
                SmallButtonLabel,
                IconButton,
                Placeholder,
                TitleField,
                PathLabel,
                WrappedTextArea;

            public readonly GUIStyle StatValue, SecondaryButtonLabel, SidebarItem, SidebarItemSelected;
            public readonly GUIStyle Title, Description, SectionTitle, Badge, Caption, Footer;

            public StyleSet(bool builtForPro) {
                BuiltForPro = builtForPro;

                // Every style uses Unity's own editor font (a null font keeps the source style's font)
                Font display = null, body = null, bodyBold = null;

                Title = Label(EditorStyles.boldLabel, display, 18, Text);
                Description = Label(EditorStyles.label, body, 11, MutedText);
                Description.wordWrap = true;

                HeaderEyebrow = Label(EditorStyles.miniLabel, display, 10, Lime);
                HeaderTitle = Label(EditorStyles.boldLabel, display, 20, Cream);
                HeaderTitle.clipping = TextClipping.Clip;
                HeaderDescription = Label(EditorStyles.label, body, 11, new Color32(184, 178, 160, 255));
                HeaderDescription.wordWrap = true;

                SectionTitle = Label(EditorStyles.boldLabel, display, 13, Text);
                SectionTitle.alignment = TextAnchor.MiddleLeft;
                SectionTitle.clipping = TextClipping.Clip;

                Badge = Label(EditorStyles.miniLabel, bodyBold, 10, AccentText);
                Badge.alignment = TextAnchor.MiddleCenter;
                Badge.padding = new RectOffset(7, 7, 0, 0);

                Caption = Label(EditorStyles.miniLabel, body, 10, MutedText);
                Footer = Label(EditorStyles.miniLabel, body, 10, MutedText);
                Footer.alignment = TextAnchor.MiddleCenter;

                // Button labels are white and tinted with GUI.contentColor, so icons take the same colour as the text
                PrimaryButtonLabel = Label(EditorStyles.boldLabel, display, 13, Color.white);
                PrimaryButtonLabel.alignment = TextAnchor.MiddleCenter;
                PrimaryButtonLabel.imagePosition = ImagePosition.ImageLeft;
                SmallButtonLabel = new GUIStyle(PrimaryButtonLabel)
                    { fontSize = 11, padding = new RectOffset(10, 10, 0, 0) };
                SecondaryButtonLabel = Label(EditorStyles.label, bodyBold, 11, Color.white);
                SecondaryButtonLabel.alignment = TextAnchor.MiddleCenter;
                SecondaryButtonLabel.imagePosition = ImagePosition.ImageLeft;

                IconButton = new GUIStyle(GUIStyle.none) {
                    alignment = TextAnchor.MiddleCenter, padding = new RectOffset(4, 4, 4, 4),
                    normal = { textColor = Color.white }, font = body
                };

                Placeholder = new GUIStyle(EditorStyles.textArea) {
                    normal = { background = null, scaledBackgrounds = null, textColor = MutedText },
                    wordWrap = true, font = body
                };
                TitleField = new GUIStyle(EditorStyles.textField) {
                    fontSize = 12, fixedHeight = 24, alignment = TextAnchor.MiddleLeft, font = bodyBold,
                    padding = new RectOffset(6, 6, 0, 0)
                };
                PathLabel = Label(EditorStyles.label, body, 11, Text);
                PathLabel.clipping = TextClipping.Clip;
                PathLabel.padding = new RectOffset(8, 8, 0, 0);
                PathLabel.alignment = TextAnchor.MiddleLeft;
                WrappedTextArea = new GUIStyle(EditorStyles.textArea) { wordWrap = true, font = body };

                Card = new GUIStyle { padding = new RectOffset(12, 12, 6, 12), margin = new RectOffset(10, 10, 5, 5) };
                Inset = new GUIStyle { padding = new RectOffset(10, 10, 8, 8), margin = new RectOffset(0, 0, 0, 6) };
                SubSection = new GUIStyle
                    { padding = new RectOffset(10, 10, 2, 10), margin = new RectOffset(0, 0, 0, 6) };
                SubSectionTitle = Label(EditorStyles.boldLabel, bodyBold, 11, Text);
                SubSectionTitle.alignment = TextAnchor.MiddleLeft;
                GroupLabel = Label(EditorStyles.miniBoldLabel, display, 10, AccentText);
                GroupLabel.margin = new RectOffset(2, 0, 10, 4);
                Callout = new GUIStyle
                    { padding = new RectOffset(16, 12, 10, 10), margin = new RectOffset(0, 0, 0, 8) };
                CalloutText = Label(EditorStyles.label, body, 11, Text);
                CalloutText.wordWrap = true;
                CalloutText.richText = true;

                StatValue = Label(EditorStyles.boldLabel, display, 24, AccentText);
                SidebarItem = Label(EditorStyles.label, body, 12, Text);
                SidebarItem.alignment = TextAnchor.MiddleLeft;
                SidebarItem.padding = new RectOffset(12, 8, 0, 0);
                SidebarItem.imagePosition = ImagePosition.ImageLeft;
                SidebarItemSelected = new GUIStyle(SidebarItem) { font = bodyBold };

                ChartLabel = Label(EditorStyles.label, body, 11, Text);
                ChartLabel.clipping = TextClipping.Clip;
                ChartValue = Label(EditorStyles.label, bodyBold, 11, MutedText);
                ChartValue.alignment = TextAnchor.UpperRight;
                ChangeText = Label(EditorStyles.label, body, 12, Text);
                ChangeText.wordWrap = true;
                ChangeText.margin = new RectOffset(0, 0, 0, 0);
                Tag = Label(EditorStyles.miniLabel, display, 9, Color.white);
                Tag.alignment = TextAnchor.MiddleCenter;
                Tag.padding = new RectOffset(6, 6, 0, 0);
                SetTextColour(SidebarItemSelected, Color.white);
            }

            private static GUIStyle Label(GUIStyle source, Font font, int size, Color colour) {
                var style = new GUIStyle(source) { fontSize = size, fontStyle = FontStyle.Normal };
                if (font != null) style.font = font;
                else if (source.fontStyle == FontStyle.Bold) style.fontStyle = FontStyle.Bold;
                SetTextColour(style, colour);
                return style;
            }

            private static void SetTextColour(GUIStyle style, Color colour) {
                style.normal.textColor = colour;
                style.hover.textColor = colour;
                style.active.textColor = colour;
                style.focused.textColor = colour;
                style.onNormal.textColor = colour;
                style.onHover.textColor = colour;
                style.onActive.textColor = colour;
                style.onFocused.textColor = colour;
            }
        }

        #endregion

        #region Drawing

        /// <summary>
        ///     Draws a filled (or outlined, when <paramref name="borderWidth" /> is set) rounded rectangle. Repaint only.
        /// </summary>
        public static void DrawRect(Rect rect, Color color, float radius = 0, float borderWidth = 0) {
            if (Event.current.type != EventType.Repaint) return;
            if (!GUI.enabled) color.a *= 0.5f;
            color.a *= GUI.color.a;
            if (color.a <= 0.001f) return;

            GUI.DrawTexture(rect, Texture2D.whiteTexture, ScaleMode.StretchToFill, true, 0, color, borderWidth, radius);
        }

        /// <summary>
        ///     Draws muted hint text over an empty field.
        /// </summary>
        public static void DrawPlaceholder(Rect rect, string text) {
            if (Event.current.type != EventType.Repaint) return;
            Placeholder.Draw(rect, new GUIContent(text), false, false, false, false);
        }

        /// <summary>
        ///     Fills a convex shape given as points in GUI space. Repaint only.
        /// </summary>
        public static void FillPolygon(Vector3[] points, Color color) {
            if (Event.current.type != EventType.Repaint || points == null || points.Length < 3) return;
            color.a *= GUI.color.a;
            if (color.a <= 0.001f) return;

            var previous = Handles.color;
            Handles.color = color;
            Handles.DrawAAConvexPolygon(points);
            Handles.color = previous;
        }

        /// <summary>
        ///     Draws a four-point sparkle (the star shape from Star In The Making).
        /// </summary>
        public static void DrawSparkle(Vector2 centre, float radius, float rotation, Color color) {
            var points = new Vector3[8];
            for (var i = 0; i < 8; i++) {
                var angle = rotation + i * Mathf.PI / 4f;
                var r = i % 2 == 0 ? radius : radius * 0.24f;
                points[i] = new Vector3(centre.x + Mathf.Cos(angle) * r, centre.y + Mathf.Sin(angle) * r, 0f);
            }

            FillPolygon(points, color);
        }

        /// <summary>
        ///     Draws a small diamond, used for stars and confetti.
        /// </summary>
        public static void DrawDiamond(Vector2 centre, Vector2 size, float rotation, Color color) {
            var cos = Mathf.Cos(rotation);
            var sin = Mathf.Sin(rotation);

            Vector3 Point(float x, float y) {
                return new Vector3(centre.x + x * cos - y * sin, centre.y + x * sin + y * cos, 0f);
            }

            FillPolygon(new[] { Point(0, -size.y), Point(size.x, 0), Point(0, size.y), Point(-size.x, 0) }, color);
        }

        /// <summary>
        ///     Draws a light streak across a rect, at <paramref name="progress" /> (0 to 1) of the way through.
        /// </summary>
        public static void DrawStreak(Rect rect, float progress, float strength = 0.45f) {
            if (Event.current.type != EventType.Repaint || progress <= 0f || progress >= 1f) return;

            var width = Mathf.Max(30f, rect.width * 0.35f);
            var x = Mathf.Lerp(rect.x - width, rect.xMax, progress);
            var streak = new Rect(x, rect.y, width, rect.height);
            var visible = Rect.MinMaxRect(Mathf.Max(streak.xMin, rect.xMin), rect.yMin,
                Mathf.Min(streak.xMax, rect.xMax), rect.yMax);
            if (visible.width <= 0f) return;

            // Only draw the part of the streak inside the rect, mapping the texture to match
            var u0 = (visible.xMin - streak.xMin) / streak.width;
            var u1 = (visible.xMax - streak.xMin) / streak.width;
            var previous = GUI.color;
            GUI.color = new Color(1f, 1f, 1f, strength * previous.a * (GUI.enabled ? 1f : 0f));
            GUI.DrawTextureWithTexCoords(visible, Streak, new Rect(u0, 0f, u1 - u0, 1f), true);
            GUI.color = previous;
        }

        /// <summary>
        ///     Draws a chevron that turns from pointing right (0) to pointing down (1).
        /// </summary>
        public static void DrawChevron(Vector2 centre, float open, Color color, float size = 4f) {
            if (Event.current.type != EventType.Repaint) return;
            color.a *= GUI.color.a;

            var angle = Mathf.Lerp(0f, 90f, open) * Mathf.Deg2Rad;
            var cos = Mathf.Cos(angle);
            var sin = Mathf.Sin(angle);

            Vector3 Point(float x, float y) {
                return new Vector3(centre.x + x * cos - y * sin, centre.y + x * sin + y * cos, 0f);
            }

            var previous = Handles.color;
            Handles.color = color;
            Handles.DrawAAPolyLine(2.2f, Point(-size * 0.5f, -size), Point(size * 0.5f, 0f), Point(-size * 0.5f, size));
            Handles.color = previous;
        }

        #endregion

        #region Icons

        [NoAutoStaticsCleanup]
        private static readonly Dictionary<string, Texture2D> IconCache = new();

        /// <summary>
        ///     Finds a built-in editor icon, preferring the dark-skin variant. Tries each name in order.
        /// </summary>
        /// <returns>The icon, or null if none of the names exist in this Unity version.</returns>
        public static Texture2D Icon(params string[] names) {
            var key = string.Join("|", names) + (Pro ? "_pro" : "");
            if (IconCache.TryGetValue(key, out var cached) && cached != null) return cached;

            Texture2D icon = null;
            foreach (var name in names) {
                if (Pro) icon = EditorGUIUtility.FindTexture("d_" + name);
                if (icon == null) icon = EditorGUIUtility.FindTexture(name);
                if (icon != null) break;
            }

            IconCache[key] = icon;
            return icon;
        }

        public static Texture2D SettingsIcon => Icon("Settings", "_Popup");
        public static Texture2D NotesIcon => Icon("TextAsset Icon");
        public static Texture2D ExportIcon => Icon("SaveAs", "Download-Available");
        public static Texture2D FolderIcon => Icon("Folder Icon", "FolderOpened Icon");
        public static Texture2D PlusIcon => Icon("Toolbar Plus");
        public static Texture2D TrashIcon => Icon("TreeEditor.Trash");
        public static Texture2D CameraIcon => Icon("Camera Icon");
        public static Texture2D BuildIcon => Icon("BuildSettings.Editor", "BuildSettings.Editor.Small");
        public static Texture2D BrushIcon => Icon("Grid.PaintTool", "ColorPicker.CycleColor");
        public static Texture2D ChartIcon => Icon("UnityEditor.ProfilerWindow", "Profiler.Memory");
        public static Texture2D PlayIcon => Icon("PlayButton");
        public static Texture2D CopyIcon => Icon("Clipboard", "TreeEditor.Duplicate");
        public static Texture2D DocsIcon => Icon("UnityEditor.InspectorWindow", "_Help");
        public static Texture2D BugIcon => Icon("console.erroricon.sml", "console.erroricon");
        public static Texture2D FeedbackIcon => Icon("console.infoicon.sml", "console.infoicon");
        public static Texture2D SocialIcon => Icon("UnityEditor.GameView", "BuildSettings.Web.Small");
        public static Texture2D ResetIcon => Icon("Refresh", "RotateTool");
        public static Texture2D LanguageIcon => Icon("BuildSettings.Web.Small", "UnityEditor.ConsoleWindow");

        #endregion
    }
}
#endif