#region Copyright

/* -----------------------------------------------------------------------------
 *  Copyright © 2024 • Chomp Studios • All Rights Reserved
 * -----------------------------------------------------------------------------
 *  Date: 21/11/2026
 *  -----------------------------------------------------------------------------
 *  Description: Houses reusable functions for UI Rendering, in the Chomp Games
 *  look, with motion: a twinkling header with shooting stars, titles that decode
 *  in, cards that fade in one after another, sections that slide open, buttons
 *  that light up, lift, press in and throw confetti, a sliding sidebar pill and
 *  numbers that count up.
 *
 *  Tools > Workflow Toolkit > Animations turns the motion off.
 *  -----------------------------------------------------------------------------
 */

#endregion

#if UNITY_EDITOR

#region Imports

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using UnityEditor;
using UnityEngine;
using Random = System.Random;
#if UNITY_6000_5_OR_NEWER
using Unity.Scripting.LifecycleManagement;
#endif

#endregion

namespace Workflow_Toolkit.Utilities {
    public class UIElements : EditorWindow {
        private const string FooterText = "• Workflow Toolkit • Copyright © 2026 • Chomp Games •";
        private const string AnimationsPref = "WorkflowToolkit.Animations";
        private const string AnimationsMenu = "Tools/Workflow Toolkit/Animations";
        private const string ScrambleGlyphs = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789#%&*+=?";
        private const float FrameInterval = 1f / 40f;

        // Everything that moves lives in this one readonly object (Fast Enter Play mode safe)
        [NoAutoStaticsCleanup]
        private static readonly MotionState State = new();

        /// <summary>
        ///     Custom &amp; reusable implementation of Unity's standard <see cref="EditorWindow.GetWindow{T}(string)" /> method
        ///     which sets a pre-determined Icon, a custom title &amp; minimum width &amp; height of the window
        /// </summary>
        /// <typeparam name="T">The type of the EditorWindow to create and display.</typeparam>
        /// <param name="windowName">The title to display on the Editor window.</param>
        /// <param name="minSize">The minimum size (width and height) of the Editor window.</param>
        /// <example>
        ///     <code>
        /// UIElements.DisplayWindow&lt;PostBuildActions&gt;("Post Build Actions", new Vector2(300, 300));
        /// </code>
        /// </example>
        public static void DisplayWindow<T>(string windowName, Vector2 minSize) where T : EditorWindow {
            var window = GetWindow<T>(windowName);

            window.minSize = minSize;
            var icon = Resources.Load<Texture2D>("workflow-logo");

            if (icon != null) icon = ResizeTexture(icon, 16, 16);

            window.titleContent = icon == null ? new GUIContent(windowName) : new GUIContent(windowName, icon);
            window.Show();

            // Replay the intro whenever the window is opened from the menu
            State.Windows.Remove(WindowKey(window));
        }

        /// <summary>
        ///     Paints the window background, enables hover highlights and drives the animations. Call at the start of a
        ///     window's OnGUI, before anything else.
        /// </summary>
        public static void TrackHover(EditorWindow window) {
            window.wantsMouseMove = true;

            var id = WindowKey(window);
            if (!State.Windows.TryGetValue(id, out var motion)) {
                motion = new WindowMotion(id, Now);
                State.Windows[id] = motion;
            }

            State.Current = window;
            State.Motion = motion;
            motion.CardIndex = 0;
            State.Frames.Clear();

            var e = Event.current;
            switch (e.type) {
                case EventType.Layout:
                    motion.LayoutDelta = Mathf.Clamp((float)(Now - motion.LastLayout), 0f, 0.1f);
                    motion.LastLayout = Now;
                    break;
                case EventType.Repaint:
                    motion.RepaintDelta = Mathf.Clamp((float)(Now - motion.LastRepaint), 0f, 0.1f);
                    motion.LastRepaint = Now;
                    GUI.DrawTexture(new Rect(0, 0, window.position.width, window.position.height),
                        Texture2D.whiteTexture,
                        ScaleMode.StretchToFill, false, 0, WorkflowStyles.WindowBackground, 0, 0);
                    break;
                case EventType.MouseMove:
                    window.Repaint();
                    break;
                case EventType.MouseDown:
                    State.MouseHeld = true;
                    window.Repaint();
                    break;
                case EventType.MouseUp:
                    State.MouseHeld = false;
                    window.Repaint();
                    break;
            }
        }

        // Works on every supported Unity version (GetInstanceID is an error in Unity 6.5, GetEntityId is missing in 2022.3)
        private static int WindowKey(EditorWindow window) {
            return window.GetHashCode();
        }

        /// <summary>
        ///     Draws a Custom Collapsible foldout for an Editor Window.
        /// </summary>
        /// <param name="title">The Title of the foldout</param>
        /// <param name="isExpanded">Reference to a boolean whether the foldout is expanded or not.</param>
        [Obsolete("Use BeginSection / EndSection for the card-style sections.")]
        public void DrawCollapsibleSection(string title, ref bool isExpanded) {
            GUILayout.BeginHorizontal();
            isExpanded = EditorGUILayout.Foldout(isExpanded, title, true);

            if (GUILayout.Button(AssetDatabase.LoadAssetAtPath<Texture2D>(" "), GUILayout.Width(15),
                    GUILayout.Height(15))) isExpanded = !isExpanded;
            GUILayout.EndHorizontal();
        }

        /// <summary>
        ///     Resizes Textures to allow rendering on the EditorWindow.
        /// </summary>
        /// <param name="tex">The texture that will be resized</param>
        /// <param name="width">The new width of the texture</param>
        /// <param name="height">The new height of the texture</param>
        /// <returns></returns>
        private static Texture2D ResizeTexture(Texture2D tex, int width, int height) {
            var rt = RenderTexture.GetTemporary(width, height);
            Graphics.Blit(tex, rt);

            var result = new Texture2D(width, height);
            RenderTexture.active = rt;
            result.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            result.Apply();

            RenderTexture.ReleaseTemporary(rt);
            return result;
        }

        #region Animations setting

        /// <summary>
        ///     Whether the windows animate. Saved per user in EditorPrefs.
        /// </summary>
        // Read-only on purpose: the Asset Store validator flags static properties with a setter
        public static bool AnimationsEnabled => EditorPrefs.GetBool(AnimationsPref, true);

        /// <summary>
        ///     Turns the animations on or off. Saved per user in EditorPrefs.
        /// </summary>
        public static void SetAnimationsEnabled(bool enabled) {
            EditorPrefs.SetBool(AnimationsPref, enabled);
        }

        [MenuItem(AnimationsMenu, false, 1000)]
        private static void ToggleAnimations() {
            SetAnimationsEnabled(!AnimationsEnabled);
        }

        [MenuItem(AnimationsMenu, true)]
        private static bool ToggleAnimationsValidate() {
            Menu.SetChecked(AnimationsMenu, AnimationsEnabled);
            return true;
        }

        #endregion

        #region Header & footer

        /// <summary>
        ///     Draws the header section of the tool window. It displays the tool's name in bold, and an informal message about the
        ///     tool.
        /// </summary>
        /// <param name="toolName">The name of the tool that is being rendered on.</param>
        /// <param name="desc">A descriptive message about the tool.</param>
        /// <example>
        ///     <code>
        ///     private void OnGUI() {
        ///         _uiElements.DrawHeader("Post-Build Actions", "This tool helps automate building");
        ///     }
        /// }
        /// </code>
        /// </example>
        public void DrawHeader(string toolName, string desc) {
            const float padding = 16;
            const float logoSize = 44;
            const float eyebrowHeight = 14;
            const float titleHeight = 26;

            var textWidth = EditorGUIUtility.currentViewWidth - logoSize - padding * 3 - 16;
            var descHeight = WorkflowStyles.HeaderDescription.CalcHeight(new GUIContent(desc), textWidth);
            var height = Mathf.Max(logoSize, eyebrowHeight + titleHeight + descHeight) + padding * 2 + 3;

            var rect = GUILayoutUtility.GetRect(0, height, GUILayout.ExpandWidth(true));
            var motion = State.Motion;
            var age = motion != null ? (float)(Now - motion.Opened) : 10f;
            var animate = AnimationsEnabled;
            if (!animate) age = 10f;

            if (Event.current.type == EventType.Repaint) {
                WorkflowStyles.DrawRect(rect, WorkflowStyles.HeaderBackground);
                if (motion != null) DrawStars(rect, motion, animate);

                // Lime underline, with a glint that travels along it
                var line = new Rect(rect.x, rect.yMax - 3, rect.width, 3);
                WorkflowStyles.DrawRect(line, WorkflowStyles.Lime);
                if (animate) WorkflowStyles.DrawStreak(line, (float)(Now * 0.28 % 1.6) - 0.3f, 0.9f);
            }

            // Logo: pops in, then breathes
            var textX = rect.x + padding;
            var logo = WorkflowStyles.Logo;
            if (logo != null) {
                var pop = Back(Mathf.Clamp01(age / 0.7f));
                var breathe = 1f + 0.035f * Mathf.Sin(age * 2.2f);
                var size = logoSize * pop * breathe;
                var centre = new Vector2(textX + logoSize * 0.5f, rect.y + padding + logoSize * 0.5f);
                var logoRect = new Rect(centre.x - size * 0.5f, centre.y - size * 0.5f, size, size);
                WithAlpha(Mathf.Clamp01(age / 0.3f), () => GUI.DrawTexture(logoRect, logo, ScaleMode.ScaleToFit));
                textX += logoSize + padding;
            }

            var width = rect.xMax - textX - padding;
            var y = rect.y + padding - 1;
            WithAlpha(Mathf.Clamp01((age - 0.1f) / 0.4f), () =>
                GUI.Label(new Rect(textX, y, width, eyebrowHeight), "WORKFLOW TOOLKIT", WorkflowStyles.HeaderEyebrow));
            WithAlpha(Mathf.Clamp01((age - 0.15f) / 0.3f), () =>
                GUI.Label(new Rect(textX, y + eyebrowHeight, width, titleHeight),
                    Decode(WorkflowStyles.Caps(toolName), age - 0.15f, 0.7f), WorkflowStyles.HeaderTitle));
            WithAlpha(Mathf.Clamp01((age - 0.35f) / 0.45f), () =>
                GUI.Label(new Rect(textX, y + eyebrowHeight + titleHeight, width, descHeight), desc,
                    WorkflowStyles.HeaderDescription));

            if (age < 1.2f) RequestFrame();
            GUILayout.Space(10);
        }

        /// <summary>
        ///     Draws the footer section of the tool window, with the watermark string <see cref="FooterText" />.
        ///     Also draws any confetti on top of the window, so call it last.
        /// </summary>
        public void DrawFooter() {
            GUILayout.FlexibleSpace();
            GUILayout.Space(8);
            var lineRect = GUILayoutUtility.GetRect(0, 1, GUILayout.ExpandWidth(true));
            WorkflowStyles.DrawRect(new Rect(lineRect.x + 12, lineRect.y, lineRect.width - 24, 1),
                WorkflowStyles.Divider);
            GUILayout.Label(FooterText, WorkflowStyles.Footer, GUILayout.Height(24));

            if (Event.current.type != EventType.Repaint) return;
            DrawParticles();

            // Keep the window ticking while anything moves (the header always twinkles while animations are on)
            if (State.Current != null && AnimationsEnabled) Queue(State.Current);
            State.WantsFrame = false;
        }

        #endregion

        #region Cards & sections

        /// <summary>
        ///     Begins a rounded card with a clickable, collapsible header. Must be closed with <see cref="EndSection" />.
        /// </summary>
        /// <param name="title">The title shown in the card header.</param>
        /// <param name="isExpanded">Reference to a boolean whether the card is expanded or not.</param>
        /// <param name="icon">Optional icon shown before the title.</param>
        /// <param name="badge">Optional text shown in a pill after the title (e.g. an item count).</param>
        /// <param name="headerAction">Optional accent button shown on the right of the header.</param>
        /// <param name="tooltip">Optional tooltip shown when hovering the header.</param>
        /// <returns>True if <paramref name="headerAction" /> was clicked.</returns>
        /// <example>
        ///     <code>
        /// if (_uiElements.BeginSection("Notes", ref _showNotes, WorkflowStyles.NotesIcon, "3", new GUIContent("New Note")))
        ///     AddNote();
        /// if (_showNotes) {
        ///     // other code
        /// }
        /// _uiElements.EndSection();
        /// </code>
        /// </example>
        public bool BeginSection(string title, ref bool isExpanded, Texture icon = null, string badge = null,
            GUIContent headerAction = null, string tooltip = null) {
            var frame = PushFrame();
            var cardRect = EditorGUILayout.BeginVertical(WorkflowStyles.Card);
            DrawCard(cardRect, true);

            return DrawSectionHeader(title, ref isExpanded, icon, badge, headerAction, tooltip, 30,
                WorkflowStyles.SectionTitle, true, frame);
        }

        /// <summary>
        ///     Closes a card started with <see cref="BeginSection" />.
        /// </summary>
        public void EndSection() {
            var frame = State.Frames.Count > 0 ? State.Frames.Pop() : null;
            if (frame != null && frame.FadeGroup) EditorGUILayout.EndFadeGroup();
            EditorGUILayout.EndVertical();
            if (frame != null) GUI.color = frame.PreviousColour;
        }

        /// <summary>
        ///     Begins a rounded card without a header. Must be closed with <see cref="EndCard" />.
        /// </summary>
        /// <param name="options">Optional layout parameters (e.g. a fixed width).</param>
        public void BeginCard(params GUILayoutOption[] options) {
            PushFrame();
            var cardRect = EditorGUILayout.BeginVertical(WorkflowStyles.Card, options);
            DrawCard(cardRect, false);
            GUILayout.Space(4);
        }

        /// <summary>
        ///     Closes a card started with <see cref="BeginCard" />.
        /// </summary>
        public void EndCard() {
            EditorGUILayout.EndVertical();
            var frame = State.Frames.Count > 0 ? State.Frames.Pop() : null;
            if (frame != null) GUI.color = frame.PreviousColour;
        }

        /// <summary>
        ///     Begins a smaller, recessed collapsible group for use inside a card. Must be closed with
        ///     <see cref="EndSubSection" />.
        /// </summary>
        /// <param name="title">The title shown in the group header.</param>
        /// <param name="isExpanded">Reference to a boolean whether the group is expanded or not.</param>
        /// <param name="tooltip">Optional tooltip shown when hovering the header.</param>
        public void BeginSubSection(string title, ref bool isExpanded, string tooltip = null) {
            var frame = new Frame { PreviousColour = GUI.color };
            State.Frames.Push(frame);
            var rect = EditorGUILayout.BeginVertical(WorkflowStyles.SubSection);
            WorkflowStyles.DrawRect(rect, WorkflowStyles.InsetBackground, 8);
            WorkflowStyles.DrawRect(rect, WorkflowStyles.Divider, 8, 1);

            DrawSectionHeader(title, ref isExpanded, null, null, null, tooltip, 26, WorkflowStyles.SubSectionTitle,
                false, frame);
        }

        /// <summary>
        ///     Closes a group started with <see cref="BeginSubSection" />.
        /// </summary>
        public void EndSubSection() {
            var frame = State.Frames.Count > 0 ? State.Frames.Pop() : null;
            if (frame != null && frame.FadeGroup) EditorGUILayout.EndFadeGroup();
            EditorGUILayout.EndVertical();
        }

        private static bool DrawSectionHeader(string title, ref bool isExpanded, Texture icon, string badge,
            GUIContent headerAction, string tooltip, float height, GUIStyle titleStyle, bool caps, Frame frame) {
            var headerRect = GUILayoutUtility.GetRect(0, height, GUILayout.ExpandWidth(true));
            var actionClicked = false;
            var titleMaxX = headerRect.xMax;

            // Drawn before the click check so the button consumes its own mouse events
            if (headerAction != null) {
                var actionWidth = WorkflowStyles.SmallButtonLabel
                    .CalcSize(new GUIContent(WorkflowStyles.Caps(headerAction.text), headerAction.image)).x + 6;
                var actionRect = new Rect(headerRect.xMax - actionWidth, headerRect.center.y - 11, actionWidth, 22);
                actionClicked = AccentButton(actionRect, headerAction, WorkflowStyles.SmallButtonLabel, false, false);
                titleMaxX = actionRect.x - 6;
            }

            // Open/close animation: the content slides open, and slides shut before it stops being drawn
            var section = Section(title, isExpanded);
            var e = Event.current;
            var hoverRect = new Rect(headerRect.x, headerRect.y, titleMaxX - headerRect.x, headerRect.height);
            if (e.type == EventType.MouseDown && e.button == 0 && hoverRect.Contains(e.mousePosition)) {
                section.Target = !section.Target;
                if (section.Target) isExpanded = true;
                e.Use();
            }

            if (!AnimationsEnabled) section.Value = section.Target ? 1f : 0f;
            else if (e.type == EventType.Layout && State.Motion != null)
                section.Value = Mathf.MoveTowards(section.Value, section.Target ? 1f : 0f,
                    State.Motion.LayoutDelta * 4.5f);
            if (!section.Target && section.Value <= 0.0001f) isExpanded = false;
            if (Mathf.Abs(section.Value - (section.Target ? 1f : 0f)) > 0.0001f) RequestFrame();

            EditorGUIUtility.AddCursorRect(hoverRect, MouseCursor.Link);
            if (!string.IsNullOrEmpty(tooltip)) GUI.Label(hoverRect, new GUIContent("", tooltip));

            var hover = Hover(hoverRect);
            var open = Smooth(section.Value);
            if (hover > 0f)
                WorkflowStyles.DrawRect(
                    new Rect(headerRect.x - 6, headerRect.y + 1, hoverRect.width + 12, headerRect.height - 2),
                    Fade(WorkflowStyles.HoverOverlay, hover), 6);

            var x = headerRect.x;
            WorkflowStyles.DrawChevron(new Vector2(x + 6, headerRect.center.y), open,
                Color.Lerp(WorkflowStyles.MutedText, WorkflowStyles.AccentText, Mathf.Max(hover, open * 0.6f)));
            x += 18;

            if (icon != null) {
                var previous = GUI.color;
                GUI.color = Color.Lerp(WorkflowStyles.MutedText, WorkflowStyles.Text, 0.4f + hover * 0.6f) *
                            new Color(1, 1, 1, previous.a);
                GUI.DrawTexture(new Rect(x, headerRect.center.y - 8, 16, 16), icon, ScaleMode.ScaleToFit);
                GUI.color = previous;
                x += 24;
            }

            var shown = caps ? WorkflowStyles.Caps(title) : title;
            var titleWidth = Mathf.Min(titleStyle.CalcSize(new GUIContent(shown)).x, titleMaxX - x);
            GUI.Label(new Rect(x + hover * 2f, headerRect.y, titleWidth, headerRect.height), shown, titleStyle);
            x += titleWidth + 8;

            if (!string.IsNullOrEmpty(badge)) {
                var badgeWidth = WorkflowStyles.Badge.CalcSize(new GUIContent(badge)).x;
                var badgeRect = new Rect(x, headerRect.center.y - 9, badgeWidth, 18);
                if (badgeRect.xMax <= titleMaxX) {
                    WorkflowStyles.DrawRect(badgeRect, Fade(WorkflowStyles.AccentText, 0.16f), 4);
                    WorkflowStyles.DrawRect(badgeRect, Fade(WorkflowStyles.AccentText, 0.35f), 4, 1);
                    GUI.Label(badgeRect, badge, WorkflowStyles.Badge);
                }
            }

            if (isExpanded) {
                var fade = AnimationsEnabled ? open : 1f;
                frame.FadeGroup = true;
                EditorGUILayout.BeginFadeGroup(fade);
                GUILayout.Space(4);
                var dividerRect = GUILayoutUtility.GetRect(0, 1, GUILayout.ExpandWidth(true));
                WorkflowStyles.DrawRect(new Rect(dividerRect.x, dividerRect.y, dividerRect.width * open, 1),
                    Color.Lerp(WorkflowStyles.Divider, WorkflowStyles.AccentText, 0.25f * (1f - open)));
                GUILayout.Space(10);
            }

            return actionClicked;
        }

        private static void DrawCard(Rect rect, bool hoverable) {
            if (Event.current.type != EventType.Repaint) return;

            var hover = hoverable ? Hover(rect, false) : 0f;
            WorkflowStyles.DrawRect(new Rect(rect.x, rect.y + 2, rect.width, rect.height), WorkflowStyles.Shadow, 12);
            WorkflowStyles.DrawRect(rect, WorkflowStyles.CardBackground, 12);
            WorkflowStyles.DrawRect(rect, Color.Lerp(WorkflowStyles.CardBorder, WorkflowStyles.StrongBorder, hover), 12,
                1);
        }

        /// <summary>
        ///     Starts a card's fade-in. Cards appear one after another when a window opens.
        /// </summary>
        private static Frame PushFrame() {
            var frame = new Frame { PreviousColour = GUI.color };
            State.Frames.Push(frame);

            var motion = State.Motion;
            if (motion == null || !AnimationsEnabled) return frame;

            var index = motion.CardIndex++;
            var age = (float)(Now - motion.Opened) - 0.25f - index * 0.09f;
            var alpha = Mathf.Clamp01(age / 0.35f);
            if (alpha < 1f) {
                GUI.color = new Color(frame.PreviousColour.r, frame.PreviousColour.g, frame.PreviousColour.b,
                    frame.PreviousColour.a * Smooth(alpha));
                RequestFrame();
            }

            return frame;
        }

        private static SectionMotion Section(string title, bool isExpanded) {
            var key = (State.Motion != null ? State.Motion.Id : 0) + "|" + title;
            if (!State.Sections.TryGetValue(key, out var section)) {
                section = new SectionMotion { Target = isExpanded, Value = isExpanded ? 1f : 0f };
                State.Sections[key] = section;
            }

            // The tool changed the value itself (e.g. reset settings): follow it
            var shownOpen = section.Target || section.Value > 0.0001f;
            if (isExpanded != shownOpen) {
                section.Target = isExpanded;
                section.Value = isExpanded ? 1f : 0f;
            }

            return section;
        }

        #endregion

        #region Small elements

        /// <summary>
        ///     Draws a small, muted heading used to group related fields inside a card.
        /// </summary>
        public void GroupLabel(string text) {
            GUILayout.Label(WorkflowStyles.Caps(text), WorkflowStyles.GroupLabel);
        }

        /// <summary>
        ///     Draws a callout box with a coloured edge, replacing <see cref="EditorGUILayout.HelpBox(string, MessageType)" />.
        ///     Supports rich text.
        /// </summary>
        /// <param name="text">The text to display.</param>
        /// <param name="warning">Uses the warning colour instead of the accent colour.</param>
        public void Callout(string text, bool warning = false) {
            var rect = EditorGUILayout.BeginVertical(WorkflowStyles.Callout);
            var edge = warning ? WorkflowStyles.WarningText : WorkflowStyles.AccentText;
            WorkflowStyles.DrawRect(rect, WorkflowStyles.InsetBackground, 8);
            WorkflowStyles.DrawRect(rect, Fade(edge, 0.25f), 8, 1);
            WorkflowStyles.DrawRect(new Rect(rect.x + 1, rect.y + 6, 3, rect.height - 12), edge, 1.5f);
            GUILayout.Label(text, WorkflowStyles.CalloutText);
            EditorGUILayout.EndVertical();
        }

        /// <summary>
        ///     Draws a highlighted number with a label underneath, for summaries and results. Numbers count up when they
        ///     change.
        /// </summary>
        /// <param name="value">The value to display.</param>
        /// <param name="label">The caption under the value.</param>
        public void StatTile(string value, string label) {
            var rect = GUILayoutUtility.GetRect(0, 64, GUILayout.ExpandWidth(true));
            var hover = Hover(rect, false);
            WorkflowStyles.DrawRect(rect, WorkflowStyles.InsetBackground, 10);
            WorkflowStyles.DrawRect(rect, Color.Lerp(WorkflowStyles.Divider, WorkflowStyles.AccentText, hover * 0.6f),
                10, 1);
            WorkflowStyles.DrawRect(
                new Rect(rect.x + 12, rect.yMax - 3, (rect.width - 24) * (0.25f + 0.75f * hover), 2),
                Fade(WorkflowStyles.AccentText, 0.5f + 0.5f * hover), 1);

            GUI.Label(new Rect(rect.x + 12, rect.y + 6, rect.width - 24, 32), CountUp(label, value),
                WorkflowStyles.StatValue);
            GUI.Label(new Rect(rect.x + 12, rect.y + 38, rect.width - 24, 16), WorkflowStyles.Caps(label),
                WorkflowStyles.Caption);
        }

        /// <summary>
        ///     Begins a recessed panel used for list items inside a card. Must be closed with <see cref="EndInset" />.
        /// </summary>
        public void BeginInset() {
            var rect = EditorGUILayout.BeginVertical(WorkflowStyles.Inset);
            var hover = Hover(rect, false);
            WorkflowStyles.DrawRect(rect, WorkflowStyles.InsetBackground, 8);
            WorkflowStyles.DrawRect(rect, Color.Lerp(WorkflowStyles.Divider, WorkflowStyles.StrongBorder, hover), 8, 1);
        }

        /// <summary>
        ///     Closes a panel started with <see cref="BeginInset" />.
        /// </summary>
        public void EndInset() {
            EditorGUILayout.EndVertical();
        }

        #endregion

        #region Buttons

        /// <summary>
        ///     Draws a full-width, accent-coloured button for a tool's main action.
        /// </summary>
        /// <param name="content">The button text, icon and tooltip.</param>
        /// <param name="height">The height of the button.</param>
        /// <param name="danger">Uses the danger colour for destructive actions.</param>
        /// <returns>True if the button was clicked.</returns>
        public bool PrimaryButton(GUIContent content, float height = 36, bool danger = false) {
            var shown = new GUIContent(WorkflowStyles.Caps(content.text), content.image, content.tooltip);
            var rect = GUILayoutUtility.GetRect(shown, WorkflowStyles.PrimaryButtonLabel,
                GUILayout.Height(height), GUILayout.ExpandWidth(true));
            return AccentButton(rect, content, WorkflowStyles.PrimaryButtonLabel, danger, true);
        }

        /// <summary>
        ///     Draws a full-width, subtle button for secondary actions (e.g. "Add File").
        /// </summary>
        /// <returns>True if the button was clicked.</returns>
        public bool SecondaryButton(GUIContent content, float height = 28) {
            var rect = GUILayoutUtility.GetRect(content, WorkflowStyles.SecondaryButtonLabel,
                GUILayout.Height(height), GUILayout.ExpandWidth(true));

            var hover = Hover(rect);
            var pressed = Pressed(rect);
            var body = pressed ? Shrink(rect, 1.5f) : new Rect(rect.x, rect.y - hover, rect.width, rect.height);

            WorkflowStyles.DrawRect(body,
                Color.Lerp(WorkflowStyles.CardBackground, WorkflowStyles.InsetBackground, 0.5f), 8);
            WorkflowStyles.DrawRect(body, Fade(WorkflowStyles.AccentText, hover * 0.08f), 8);
            WorkflowStyles.DrawRect(body, Color.Lerp(WorkflowStyles.StrongBorder, WorkflowStyles.AccentText, hover), 8,
                1);

            var iconSize = EditorGUIUtility.GetIconSize();
            var contentColour = GUI.contentColor;
            EditorGUIUtility.SetIconSize(new Vector2(14, 14));
            GUI.contentColor = Color.Lerp(WorkflowStyles.Text, WorkflowStyles.AccentText, hover);
            var clicked = GUI.Button(body, content, WorkflowStyles.SecondaryButtonLabel);
            GUI.contentColor = contentColour;
            EditorGUIUtility.SetIconSize(iconSize);

            if (clicked) Burst(rect, 12, 180f);
            return clicked;
        }

        /// <summary>
        ///     Draws a full-width navigation item for sidebars. The selection pill slides between items.
        /// </summary>
        /// <param name="content">The item text, icon and tooltip.</param>
        /// <param name="selected">Whether this item is the current page.</param>
        /// <returns>True if the item was clicked.</returns>
        public bool SidebarItem(GUIContent content, bool selected) {
            var rect = GUILayoutUtility.GetRect(content, WorkflowStyles.SidebarItem, GUILayout.Height(30),
                GUILayout.ExpandWidth(true));
            var hover = Hover(rect);
            var motion = State.Motion;

            if (selected && Event.current.type == EventType.Repaint) {
                var pill = rect;
                if (motion != null && AnimationsEnabled) {
                    if (!motion.SidebarReady) {
                        motion.SidebarY = rect.y;
                        motion.SidebarReady = true;
                    }

                    motion.SidebarY = Mathf.Lerp(motion.SidebarY, rect.y, 1f - Mathf.Exp(-motion.RepaintDelta * 14f));
                    if (Mathf.Abs(motion.SidebarY - rect.y) > 0.3f) RequestFrame();
                    else motion.SidebarY = rect.y;
                    pill.y = motion.SidebarY;
                }

                WorkflowStyles.DrawRect(pill, WorkflowStyles.Accent, 8);
                WorkflowStyles.DrawStreak(pill, (float)(Now * 0.3 % 2.2) - 0.6f, 0.35f);
            }
            else if (hover > 0f) {
                WorkflowStyles.DrawRect(rect, Fade(WorkflowStyles.HoverOverlay, hover * 1.6f), 8);
                WorkflowStyles.DrawRect(new Rect(rect.x + 2, rect.y + 8, 3, rect.height - 16),
                    Fade(WorkflowStyles.AccentText, hover), 1.5f);
            }

            var iconSize = EditorGUIUtility.GetIconSize();
            var contentColour = GUI.contentColor;
            EditorGUIUtility.SetIconSize(new Vector2(16, 16));
            var style = selected ? WorkflowStyles.SidebarItemSelected : WorkflowStyles.SidebarItem;
            if (selected) GUI.contentColor = WorkflowStyles.OnAccent;
            var shifted = new Rect(rect.x + (selected ? 0f : hover * 3f), rect.y, rect.width, rect.height);
            var clicked = GUI.Button(shifted, content, style);
            GUI.contentColor = contentColour;
            EditorGUIUtility.SetIconSize(iconSize);

            return clicked;
        }

        /// <summary>
        ///     Draws a small, borderless icon button with a hover highlight.
        /// </summary>
        /// <param name="icon">The icon to show.</param>
        /// <param name="fallbackText">Text shown if the icon is missing in this Unity version.</param>
        /// <param name="tooltip">The tooltip text displayed when hovering.</param>
        /// <param name="danger">Uses a red hover highlight for destructive actions.</param>
        /// <returns>True if the button was clicked.</returns>
        public bool IconButton(Texture icon, string fallbackText, string tooltip, bool danger = false) {
            var rect = GUILayoutUtility.GetRect(24, 24, GUILayout.Width(24), GUILayout.Height(24));
            var hover = Hover(rect);
            var pressed = Pressed(rect);
            var body = pressed ? Shrink(rect, 1.5f) : rect;
            var tint = danger ? WorkflowStyles.DangerText : WorkflowStyles.AccentText;

            if (hover > 0f) {
                WorkflowStyles.DrawRect(body, Fade(tint, 0.18f * hover), 6);
                WorkflowStyles.DrawRect(body, Fade(tint, 0.5f * hover), 6, 1);
            }

            var contentColour = GUI.contentColor;
            GUI.contentColor = Color.Lerp(WorkflowStyles.MutedText, tint, hover);
            var content = icon != null ? new GUIContent(icon, tooltip) : new GUIContent(fallbackText, tooltip);
            var clicked = GUI.Button(body, content, WorkflowStyles.IconButton);
            GUI.contentColor = contentColour;

            if (clicked && !danger) Burst(rect, 8, 140f);
            return clicked;
        }

        /// <summary>
        ///     Draws a read-only path pill with a folder button that opens a folder picker.
        /// </summary>
        /// <param name="displayPath">The (shortened) path shown in the pill.</param>
        /// <param name="fullPath">The full path, shown as the pill's tooltip.</param>
        /// <param name="tooltip">The tooltip for the folder button.</param>
        /// <returns>True if the folder button was clicked.</returns>
        public bool PathField(string displayPath, string fullPath, string tooltip) {
            EditorGUILayout.BeginHorizontal();

            var content = new GUIContent(displayPath, fullPath);
            var rect = GUILayoutUtility.GetRect(content, WorkflowStyles.PathLabel, GUILayout.Height(24),
                GUILayout.ExpandWidth(true));
            var hover = Hover(rect, false);
            WorkflowStyles.DrawRect(rect, WorkflowStyles.InsetBackground, 6);
            WorkflowStyles.DrawRect(rect, Color.Lerp(WorkflowStyles.Divider, WorkflowStyles.StrongBorder, hover), 6, 1);
            GUI.Label(rect, content, WorkflowStyles.PathLabel);

            GUILayout.Space(4);
            var clicked = IconButton(WorkflowStyles.FolderIcon, "…", tooltip);

            EditorGUILayout.EndHorizontal();
            return clicked;
        }

        private static bool AccentButton(Rect rect, GUIContent content, GUIStyle labelStyle, bool danger,
            bool primary) {
            var hover = Hover(rect);
            var pressed = Pressed(rect);
            var lift = primary && !pressed ? hover * 1.5f : 0f;
            var body = pressed ? Shrink(rect, 1.5f) : new Rect(rect.x, rect.y - lift, rect.width, rect.height);

            var fill = danger
                ? Color.Lerp(WorkflowStyles.DangerFill, WorkflowStyles.DangerFillHover, hover)
                : pressed
                    ? WorkflowStyles.AccentPressed
                    : Color.Lerp(WorkflowStyles.Accent, WorkflowStyles.AccentHover, hover);

            if (primary)
                WorkflowStyles.DrawRect(new Rect(rect.x, rect.y + 2 + lift, rect.width, rect.height),
                    WorkflowStyles.Shadow, 8);
            WorkflowStyles.DrawRect(body, fill, 8);
            if (!EditorGUIUtility.isProSkin && !danger)
                WorkflowStyles.DrawRect(body, WorkflowStyles.StrongBorder, 8, 1);

            // A light sweeps across main buttons every few seconds, and straight away on hover
            if (primary && AnimationsEnabled && GUI.enabled) {
                var cycle = (float)((Now + rect.y * 0.004) % 3.6) / 0.9f;
                WorkflowStyles.DrawStreak(body, cycle, 0.5f);
            }

            var iconSize = EditorGUIUtility.GetIconSize();
            var contentColour = GUI.contentColor;
            EditorGUIUtility.SetIconSize(new Vector2(14, 14));
            GUI.contentColor = danger ? WorkflowStyles.OnDanger : WorkflowStyles.OnAccent;
            var shown = new GUIContent(WorkflowStyles.Caps(content.text), content.image, content.tooltip);
            var clicked = GUI.Button(body, shown, labelStyle);
            GUI.contentColor = contentColour;
            EditorGUIUtility.SetIconSize(iconSize);

            if (clicked && !danger) Burst(rect, primary ? 36 : 14, primary ? 420f : 220f);
            return clicked;
        }

        #endregion

        #region Charts & changelog

        /// <summary>
        ///     One bar in a <see cref="BarChart" />.
        /// </summary>
        public struct ChartRow {
            public string Label;
            public double Value;
            public string ValueText;
            public Color Colour;
            public string Tooltip;
        }

        /// <summary>
        ///     Draws a horizontal bar chart: a strip showing each row's share of the total, then one labelled bar per row.
        ///     Bars grow in whenever the numbers change.
        /// </summary>
        /// <param name="key">A name for this chart, unique within the window.</param>
        /// <param name="rows">The rows, in the order to show them.</param>
        /// <returns>The index of the row that was clicked, or -1.</returns>
        public int BarChart(string key, IList<ChartRow> rows) {
            if (rows == null || rows.Count == 0) return -1;

            double total = 0, max = 0;
            var signature = new StringBuilder();
            foreach (var row in rows) {
                total += Math.Max(0, row.Value);
                max = Math.Max(max, row.Value);
                signature.Append(row.Label).Append('=').Append(row.Value.ToString("R", CultureInfo.InvariantCulture))
                    .Append(';');
            }

            var start = ChartStart(key, signature.ToString());

            // Share of the total, as one segmented strip
            var strip = GUILayoutUtility.GetRect(0, 12, GUILayout.ExpandWidth(true));
            WorkflowStyles.DrawRect(strip, WorkflowStyles.InsetBackground, 6);
            var x = strip.x;
            for (var i = 0; i < rows.Count; i++) {
                var share = total > 0 ? (float)(Math.Max(0, rows[i].Value) / total) : 0f;
                var width = strip.width * share;
                var shown = width * Grow(start, i);
                if (shown >= 2f)
                    WorkflowStyles.DrawRect(new Rect(x, strip.y, shown - 1f, strip.height), rows[i].Colour, 3);
                x += width;
            }

            if (AnimationsEnabled) WorkflowStyles.DrawStreak(strip, (float)(Now * 0.25 % 1.8) - 0.4f, 0.25f);
            GUILayout.Space(12);

            var clicked = -1;
            for (var i = 0; i < rows.Count; i++) {
                var row = rows[i];
                var rect = GUILayoutUtility.GetRect(0, 32, GUILayout.ExpandWidth(true));
                var hover = Hover(rect);
                var grow = Grow(start, i);

                if (hover > 0f)
                    WorkflowStyles.DrawRect(new Rect(rect.x - 6, rect.y, rect.width + 12, rect.height),
                        Fade(WorkflowStyles.HoverOverlay, hover * 1.5f), 6);

                WithAlpha(Mathf.Clamp01(grow * 2f), () => {
                    WorkflowStyles.DrawRect(new Rect(rect.x, rect.y + 6, 10, 10), row.Colour, 3);
                    var valueWidth = Mathf.Min(120f, rect.width * 0.4f);
                    GUI.Label(new Rect(rect.x + 18 + hover * 2f, rect.y + 2, rect.width - 18 - valueWidth, 18),
                        row.Label, WorkflowStyles.ChartLabel);
                    GUI.Label(new Rect(rect.xMax - valueWidth, rect.y + 2, valueWidth, 18), row.ValueText,
                        WorkflowStyles.ChartValue);
                });

                var track = new Rect(rect.x + 18, rect.y + 23, rect.width - 18, 5);
                WorkflowStyles.DrawRect(track, WorkflowStyles.InsetBackground, 2.5f);
                var fill = max > 0 ? (float)(row.Value / max) : 0f;
                var bar = new Rect(track.x, track.y - hover, Mathf.Max(5f, track.width * fill * grow),
                    track.height + hover * 2f);
                if (fill > 0f) {
                    WorkflowStyles.DrawRect(bar, row.Colour, 2.5f);
                    if (hover > 0f) WorkflowStyles.DrawStreak(bar, (float)(Now * 0.9 % 1.3), 0.6f * hover);
                }

                if (!string.IsNullOrEmpty(row.Tooltip)) {
                    GUI.Label(rect, new GUIContent("", row.Tooltip));
                    EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
                }

                var e = Event.current;
                if (e.type == EventType.MouseDown && e.button == 0 && rect.Contains(e.mousePosition)) {
                    clicked = i;
                    Burst(rect, 10, 160f);
                    e.Use();
                }
            }

            return clicked;
        }

        /// <summary>
        ///     Draws a version number as a heading, with an optional pill (e.g. "Latest") beside it.
        /// </summary>
        public void VersionHeading(string version, string badge = null) {
            var content = new GUIContent(WorkflowStyles.Caps(version));
            var rect = GUILayoutUtility.GetRect(content, WorkflowStyles.Title, GUILayout.Height(28),
                GUILayout.ExpandWidth(true));
            var width = WorkflowStyles.Title.CalcSize(content).x;
            GUI.Label(new Rect(rect.x, rect.y, width, rect.height), content, WorkflowStyles.Title);

            if (!string.IsNullOrEmpty(badge)) {
                var badgeContent = new GUIContent(WorkflowStyles.Caps(badge));
                var badgeWidth = WorkflowStyles.Tag.CalcSize(badgeContent).x;
                var badgeRect = new Rect(rect.x + width + 10, rect.center.y - 9, badgeWidth, 18);
                var pulse = AnimationsEnabled ? 0.5f + 0.5f * Mathf.Sin((float)Now * 3f) : 0f;
                WorkflowStyles.DrawRect(Shrink(badgeRect, -2f * pulse), Fade(WorkflowStyles.Lime, 0.25f * pulse), 6);
                WorkflowStyles.DrawRect(badgeRect, WorkflowStyles.Lime, 4);
                var contentColour = GUI.contentColor;
                GUI.contentColor = WorkflowStyles.OnAccent;
                GUI.Label(badgeRect, badgeContent, WorkflowStyles.Tag);
                GUI.contentColor = contentColour;
            }

            GUILayout.Space(4);
        }

        /// <summary>
        ///     Draws one line of a changelog: a coloured tag ("New", "Improved", "Fixed") and the text beside it.
        /// </summary>
        /// <param name="tag">The tag text.</param>
        /// <param name="colour">The tag colour.</param>
        /// <param name="text">What changed.</param>
        /// <param name="index">The line's position in the list, so lines can appear one after another.</param>
        public void ChangeItem(string tag, Color colour, string text, int index = 0) {
            var motion = State.Motion;
            var alpha = 1f;
            if (motion != null && AnimationsEnabled) {
                alpha = Mathf.Clamp01(((float)(Now - motion.PageShown) - 0.1f - index * 0.08f) / 0.3f);
                if (alpha < 1f) RequestFrame();
            }

            var previous = GUI.color;
            GUI.color = new Color(previous.r, previous.g, previous.b, previous.a * Smooth(alpha));

            EditorGUILayout.BeginHorizontal();
            var tagContent = new GUIContent(WorkflowStyles.Caps(tag));
            var tagRect = GUILayoutUtility.GetRect(tagContent, WorkflowStyles.Tag, GUILayout.Width(84),
                GUILayout.Height(18));
            var pill = new Rect(tagRect.x, tagRect.y + 1,
                Mathf.Min(tagRect.width, WorkflowStyles.Tag.CalcSize(tagContent).x), 18);
            WorkflowStyles.DrawRect(pill, Fade(colour, 0.18f), 4);
            WorkflowStyles.DrawRect(pill, Fade(colour, 0.6f), 4, 1);
            var contentColour = GUI.contentColor;
            GUI.contentColor = colour;
            GUI.Label(pill, tagContent, WorkflowStyles.Tag);
            GUI.contentColor = contentColour;

            GUILayout.Space(6);
            GUILayout.Label(text, WorkflowStyles.ChangeText);
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(8);

            GUI.color = previous;
        }

        /// <summary>
        ///     Restarts the entrance animations of a page (e.g. when switching pages in a sidebar window).
        /// </summary>
        public static void ReplayPageAnimations(EditorWindow window) {
            if (window != null && State.Windows.TryGetValue(WindowKey(window), out var motion)) motion.PageShown = Now;
        }

        private static double ChartStart(string key, string signature) {
            var fullKey = (State.Motion != null ? State.Motion.Id : 0) + "|" + key;
            if (!State.Charts.TryGetValue(fullKey, out var chart) || chart.Signature != signature) {
                chart = new ChartMotion { Signature = signature, Start = Now };
                State.Charts[fullKey] = chart;
            }

            return chart.Start;
        }

        private static float Grow(double start, int index) {
            if (!AnimationsEnabled) return 1f;
            var t = Mathf.Clamp01(((float)(Now - start) - index * 0.05f) / 0.7f);
            if (t < 1f) RequestFrame();
            return 1f - Mathf.Pow(1f - t, 3f);
        }

        #endregion

        #region Animation helpers

        private static double Now => EditorApplication.timeSinceStartup;

        /// <summary>Asks for another frame soon (something is still moving).</summary>
        private static void RequestFrame() {
            State.WantsFrame = true;
        }

        private static void Queue(EditorWindow window) {
            State.RepaintQueue.Add(window);
            if (State.Hooked) return;
            EditorApplication.update += Tick;
            State.Hooked = true;
        }

        // Repaints the windows that are animating, about 40 times a second
        private static void Tick() {
            if (State.RepaintQueue.Count == 0 || Now - State.LastTick < FrameInterval) return;
            State.LastTick = Now;

            State.Scratch.Clear();
            State.Scratch.AddRange(State.RepaintQueue);
            State.RepaintQueue.Clear();
            foreach (var window in State.Scratch)
                if (window != null)
                    window.Repaint();
        }

        /// <summary>A 0-1 hover amount that eases in and out instead of snapping.</summary>
        private static float Hover(Rect rect, bool needsEnabled = true) {
            var hovered = (!needsEnabled || GUI.enabled) && rect.Contains(Event.current.mousePosition);
            if (!AnimationsEnabled || State.Motion == null) return hovered ? 1f : 0f;

            var key = HoverKey(rect);
            State.Hovers.TryGetValue(key, out var value);
            if (Event.current.type == EventType.Repaint) {
                var target = hovered ? 1f : 0f;
                value = Mathf.MoveTowards(value, target, State.Motion.RepaintDelta * 7f);
                if (Mathf.Abs(value - target) > 0.001f) RequestFrame();
                if (value <= 0f) State.Hovers.Remove(key);
                else State.Hovers[key] = value;
            }

            return Smooth(value);
        }

        private static bool Pressed(Rect rect) {
            return State.MouseHeld && GUI.enabled && rect.Contains(Event.current.mousePosition);
        }

        private static string HoverKey(Rect rect) {
            var id = State.Motion != null ? State.Motion.Id : 0;
            return id + ":" + Mathf.RoundToInt(rect.x) + ":" + Mathf.RoundToInt(rect.y) + ":" +
                   Mathf.RoundToInt(rect.width);
        }

        /// <summary>Scrambles text and resolves it left to right over <paramref name="duration" /> seconds.</summary>
        private static string Decode(string text, float age, float duration) {
            if (string.IsNullOrEmpty(text) || age >= duration || !AnimationsEnabled) return text;
            if (age <= 0f) age = 0f;

            var revealed = age / duration * text.Length;
            var builder = new StringBuilder(text.Length);
            var seed = (int)(Now * 30);
            for (var i = 0; i < text.Length; i++) {
                var c = text[i];
                if (char.IsWhiteSpace(c) || i < revealed) builder.Append(c);
                else builder.Append(ScrambleGlyphs[Mathf.Abs((seed + i * 7919) % ScrambleGlyphs.Length)]);
            }

            return builder.ToString();
        }

        /// <summary>Counts a numeric value up from what it showed before; other text is shown as it is.</summary>
        private static string CountUp(string key, string value) {
            if (!AnimationsEnabled || State.Motion == null) return value;
            if (!double.TryParse(value, NumberStyles.Any, CultureInfo.CurrentCulture, out var target)) return value;

            var fullKey = State.Motion.Id + "|" + key;
            if (!State.Counts.TryGetValue(fullKey, out var count)) {
                count = new CountMotion { From = 0, To = target, Start = Now };
                State.Counts[fullKey] = count;
            }
            else if (Math.Abs(count.To - target) > 0.0001) {
                count.From = count.Current;
                count.To = target;
                count.Start = Now;
            }

            var t = Mathf.Clamp01((float)((Now - count.Start) / 0.9));
            count.Current = count.From + (count.To - count.From) * (1 - Math.Pow(1 - t, 3));
            if (t >= 1f) return value;

            RequestFrame();
            var decimals = value.Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator) ? 1 : 0;
            var grouped = value.Contains(CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator);
            return count.Current.ToString((grouped ? "N" : "F") + decimals, CultureInfo.CurrentCulture);
        }

        private static void DrawStars(Rect rect, WindowMotion motion, bool animate) {
            var time = animate ? (float)(Now - motion.Opened) : 0f;

            foreach (var star in motion.Stars) {
                var twinkle = 0.55f + 0.45f * Mathf.Sin(time * star.Speed + star.Phase);
                var colour = star.Lime ? WorkflowStyles.Lime : WorkflowStyles.Cream;
                colour.a = star.Brightness * twinkle * Mathf.Clamp01(time / 0.8f + (animate ? 0f : 1f));
                var centre = new Vector2(rect.x + star.Position.x * rect.width, rect.y + star.Position.y * rect.height);
                if (star.Sparkle)
                    WorkflowStyles.DrawSparkle(centre, star.Size * (0.8f + 0.35f * twinkle), time * 0.4f + star.Phase,
                        colour);
                else WorkflowStyles.DrawDiamond(centre, Vector2.one * star.Size, 0f, colour);
            }

            if (!animate) return;

            // A shooting star every few seconds
            if (Now >= motion.NextShot && motion.ShotStart < 0) {
                motion.ShotStart = Now;
                motion.ShotFrom = new Vector2(0.35f + (float)motion.Random.NextDouble() * 0.6f,
                    (float)motion.Random.NextDouble() * 0.3f);
            }

            if (motion.ShotStart < 0) return;

            var age = (float)(Now - motion.ShotStart);
            if (age > 1f) {
                motion.ShotStart = -1;
                motion.NextShot = Now + 4 + motion.Random.NextDouble() * 6;
                return;
            }

            var direction = new Vector2(-1f, 0.38f).normalized;
            var head = new Vector2(rect.x + motion.ShotFrom.x * rect.width, rect.y + motion.ShotFrom.y * rect.height) +
                       direction * (age * 520f);
            var fade = 1f - age;
            for (var i = 0; i < 10; i++) {
                var strength = (1f - i / 10f) * fade;
                var point = head - direction * (i * 9f);
                if (!rect.Contains(point)) continue;
                WorkflowStyles.DrawDiamond(point, new Vector2(2.4f * (1f - i / 12f), 1.2f),
                    Mathf.Atan2(direction.y, direction.x),
                    new Color(1f, 0.965f, 0.851f, strength * 0.9f));
            }

            if (rect.Contains(head))
                WorkflowStyles.DrawSparkle(head, 4f, age * 6f, new Color(0.804f, 0.984f, 0.153f, fade));
        }

        /// <summary>Throws confetti from a rect (in the current GUI space).</summary>
        private static void Burst(Rect rect, int count, float speed) {
            if (!AnimationsEnabled || State.Motion == null) return;

            var origin = GUIUtility.GUIToScreenPoint(rect.center);
            var random = State.Motion.Random;
            for (var i = 0; i < count; i++) {
                var angle = (float)(random.NextDouble() * Math.PI * 2);
                var power = speed * (0.35f + (float)random.NextDouble() * 0.65f);
                var pick = random.Next(10);
                State.Particles.Add(new Particle {
                    Window = State.Motion.Id,
                    Position = origin + new Vector2((float)(random.NextDouble() - 0.5) * rect.width * 0.6f, 0f),
                    Velocity = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle) - 0.6f) * power,
                    Size = new Vector2(2f + (float)random.NextDouble() * 2.5f, 2f + (float)random.NextDouble() * 4f),
                    Rotation = (float)random.NextDouble() * 6.28f,
                    Spin = ((float)random.NextDouble() - 0.5f) * 14f,
                    Life = 0f,
                    MaxLife = 0.8f + (float)random.NextDouble() * 0.6f,
                    Colour = pick < 6 ? WorkflowStyles.Lime : pick < 9 ? WorkflowStyles.Cream : WorkflowStyles.Warning
                });
            }
        }

        private static void DrawParticles() {
            var motion = State.Motion;
            if (motion == null) return;

            for (var i = State.Particles.Count - 1; i >= 0; i--) {
                var particle = State.Particles[i];
                if (particle.Window != motion.Id) continue;

                particle.Life += motion.RepaintDelta;
                if (particle.Life >= particle.MaxLife) {
                    State.Particles.RemoveAt(i);
                    continue;
                }

                particle.Velocity.y += 900f * motion.RepaintDelta;
                particle.Velocity *= 1f - 1.4f * motion.RepaintDelta;
                particle.Position += particle.Velocity * motion.RepaintDelta;
                particle.Rotation += particle.Spin * motion.RepaintDelta;

                var fade = 1f - particle.Life / particle.MaxLife;
                var colour = particle.Colour;
                colour.a = Mathf.Clamp01(fade * 1.6f);
                var point = GUIUtility.ScreenToGUIPoint(particle.Position);
                WorkflowStyles.DrawDiamond(point, particle.Size * (0.5f + 0.5f * fade), particle.Rotation, colour);
                RequestFrame();
            }
        }

        private static void WithAlpha(float alpha, Action draw) {
            if (alpha <= 0f) return;
            var previous = GUI.color;
            GUI.color = new Color(previous.r, previous.g, previous.b, previous.a * alpha);
            draw();
            GUI.color = previous;
        }

        private static Color Fade(Color colour, float alpha) {
            colour.a *= alpha;
            return colour;
        }

        private static Rect Shrink(Rect rect, float amount) {
            return new Rect(rect.x + amount, rect.y + amount, rect.width - amount * 2, rect.height - amount * 2);
        }

        private static float Smooth(float t) {
            t = Mathf.Clamp01(t);
            return t * t * (3f - 2f * t);
        }

        private static float Back(float t) {
            const float s = 1.70158f;
            t -= 1f;
            return t * t * ((s + 1f) * t + s) + 1f;
        }

        private sealed class MotionState {
            public readonly Dictionary<string, ChartMotion> Charts = new();
            public readonly Dictionary<string, CountMotion> Counts = new();
            public readonly Stack<Frame> Frames = new();
            public readonly Dictionary<string, float> Hovers = new();
            public readonly List<Particle> Particles = new();
            public readonly HashSet<EditorWindow> RepaintQueue = new();
            public readonly List<EditorWindow> Scratch = new();
            public readonly Dictionary<string, SectionMotion> Sections = new();
            public readonly Dictionary<int, WindowMotion> Windows = new();
            public EditorWindow Current;
            public bool Hooked;
            public double LastTick;
            public WindowMotion Motion;
            public bool MouseHeld;
            public bool WantsFrame;
        }

        private sealed class WindowMotion {
            public readonly int Id;
            public readonly double Opened;
            public readonly Random Random;
            public readonly Star[] Stars;
            public int CardIndex;
            public double LastLayout, LastRepaint, PageShown;
            public float LayoutDelta, RepaintDelta;
            public double NextShot, ShotStart = -1;
            public Vector2 ShotFrom;
            public bool SidebarReady;
            public float SidebarY;

            public WindowMotion(int id, double now) {
                Id = id;
                Opened = now;
                LastLayout = LastRepaint = PageShown = now;
                Random = new Random(id);
                NextShot = now + 2.5;

                Stars = new Star[28];
                for (var i = 0; i < Stars.Length; i++) {
                    var sparkle = Random.NextDouble() < 0.12;
                    Stars[i] = new Star {
                        Position = new Vector2((float)Random.NextDouble(), 0.08f + (float)Random.NextDouble() * 0.8f),
                        Size = sparkle
                            ? 3f + (float)Random.NextDouble() * 2.5f
                            : 0.7f + (float)Random.NextDouble() * 1.2f,
                        Phase = (float)(Random.NextDouble() * Math.PI * 2),
                        Speed = 0.7f + (float)Random.NextDouble() * 2f,
                        Brightness = 0.25f + (float)Random.NextDouble() * 0.55f,
                        Sparkle = sparkle,
                        Lime = Random.NextDouble() < 0.2
                    };
                }
            }
        }

        private struct Star {
            public Vector2 Position;
            public float Size, Phase, Speed, Brightness;
            public bool Sparkle, Lime;
        }

        private sealed class SectionMotion {
            public bool Target;
            public float Value;
        }

        private sealed class ChartMotion {
            public string Signature;
            public double Start;
        }

        private sealed class CountMotion {
            public double From, To, Current;
            public double Start;
        }

        private sealed class Frame {
            public bool FadeGroup;
            public Color PreviousColour;
        }

        private sealed class Particle {
            public Color Colour;
            public float Life, MaxLife, Rotation, Spin;
            public Vector2 Position, Size, Velocity;
            public int Window;
        }

        #endregion
    }
}
#endif