// 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 System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    /// <summary>
    /// Shows what the package check found, in plain words: before an import (import, import without the flagged
    /// files, or cancel), after files were held back on arrival (put back or delete), for a project check, and
    /// the quarantine folder.
    /// </summary>
    internal sealed class WPFMASafetyWindow : EditorWindow
    {
        private enum Mode
        {
            Package,
            Arrivals,
            Project,
            Quarantine
        }

        private static Color Background => WPFMA.Editor.WPFMAProjectKindWindow.Background;
        private static Color Panel => WPFMA.Editor.WPFMAProjectKindWindow.Panel;
        private static Color PanelHover => WPFMA.Editor.WPFMAProjectKindWindow.PanelHover;
        private static Color Border => WPFMA.Editor.WPFMAProjectKindWindow.Border;
        private static Color Accent => WPFMA.Editor.WPFMAProjectKindWindow.Accent;
        private static Color AccentDim => WPFMA.Editor.WPFMAProjectKindWindow.AccentDim;
        private static Color AccentText => WPFMA.Editor.WPFMAProjectKindWindow.AccentText;
        private static Color TitleText => WPFMA.Editor.WPFMAProjectKindWindow.TitleText;
        private static Color BodyText => WPFMA.Editor.WPFMAProjectKindWindow.BodyText;
        private static Color DimText => WPFMA.Editor.WPFMAProjectKindWindow.DimText;
        private static readonly Color Red = new Color(230f / 255f, 107f / 255f, 115f / 255f);
        private static readonly Color RedDim = new Color(120f / 255f, 46f / 255f, 52f / 255f);
        private static readonly Color Amber = new Color(239f / 255f, 159f / 255f, 39f / 255f);
        private static readonly Color Green = new Color(93f / 255f, 202f / 255f, 165f / 255f);

        [NonSerialized] private Mode mode;
        [NonSerialized] private SafetyReport report;
        [NonSerialized] private string headline;
        [NonSerialized] private Action<WPFMASafety.Choice> choose;
        [NonSerialized] private bool chosen;
        [NonSerialized] private List<QuarantinedFile> held = new List<QuarantinedFile>();
        [NonSerialized] private List<SafetyItem> noticed = new List<SafetyItem>();
        [NonSerialized] private readonly HashSet<string> open = new HashSet<string>();
        [NonSerialized] private bool showNormal;
        [NonSerialized] private Vector2 scroll;
        [NonSerialized] private GUIStyle titleStyle, body, dim, mono, rowTitle, rowBody, tag, buttonText, banner;

        // ---- Opening ----------------------------------------------------------------------------------------------------

        internal static void ShowPackage(SafetyReport report, Action<WPFMASafety.Choice> choose)
        {
            var window = Make(Mode.Package, "Check before importing", new Vector2(620f, 600f));
            window.report = report;
            window.choose = choose;
        }

        internal static void ShowArrivals(List<QuarantinedFile> held, List<SafetyItem> noticed)
        {
            var existing = Resources.FindObjectsOfTypeAll<WPFMASafetyWindow>().FirstOrDefault(w => w.mode == Mode.Arrivals);
            if (existing != null)
            {
                existing.held.AddRange(held);
                existing.noticed.AddRange(noticed);
                existing.Focus();
                return;
            }
            var window = Make(Mode.Arrivals, "Package safety", new Vector2(620f, 560f));
            window.held = held;
            window.noticed = noticed;
        }

        internal static void ShowProject(SafetyReport report, string headline = null)
        {
            var window = Make(Mode.Project, "Project check", new Vector2(620f, 600f));
            window.report = report;
            window.headline = headline;
        }

        internal static void ShowQuarantine()
        {
            var window = Make(Mode.Quarantine, "Quarantine", new Vector2(620f, 520f));
            window.held = WPFMASafety.Quarantined();
        }

        private static WPFMASafetyWindow Make(Mode mode, string title, Vector2 size)
        {
            foreach (var old in Resources.FindObjectsOfTypeAll<WPFMASafetyWindow>())
                if (old.mode == mode && mode != Mode.Package)
                    old.Close();

            var window = CreateInstance<WPFMASafetyWindow>();
            window.mode = mode;
            window.titleContent = new GUIContent(title);
            window.minSize = new Vector2(480f, 380f);
            var main = EditorGUIUtility.GetMainWindowPosition();
            window.position = new Rect(main.x + (main.width - size.x) * 0.5f, main.y + (main.height - size.y) * 0.5f, size.x, size.y);
            window.ShowUtility();
            return window;
        }

        private void OnEnable()
        {
            wantsMouseMove = true;
        }

        private void OnDestroy()
        {
            // Closing the window is the same as Cancel.
            Pick(WPFMASafety.Choice.Cancel);
        }

        private void Pick(WPFMASafety.Choice choice)
        {
            if (chosen || choose == null)
                return;
            chosen = true;
            var callback = choose;
            choose = null;
            EditorApplication.delayCall += () => callback(choice);
        }

        // ---- Drawing ----------------------------------------------------------------------------------------------------

        private void OnGUI()
        {
            Styles();
            if (Event.current.type == EventType.MouseMove)
                Repaint();
            EditorGUI.DrawRect(new Rect(0f, 0f, position.width, position.height), Background);

            // Opened from a previous session (domain reload): nothing to show any more.
            if ((mode == Mode.Package || mode == Mode.Project) && report == null)
            {
                Close();
                return;
            }

            GUILayout.Space(14f);
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(18f);
                using (new GUILayout.VerticalScope())
                {
                    DrawTop();
                    GUILayout.Space(10f);
                    scroll = GUILayout.BeginScrollView(scroll, GUIStyle.none, GUI.skin.verticalScrollbar);
                    switch (mode)
                    {
                        case Mode.Package:
                        case Mode.Project:
                            DrawReport();
                            break;
                        case Mode.Arrivals:
                            DrawArrivals();
                            break;
                        case Mode.Quarantine:
                            DrawQuarantine();
                            break;
                    }
                    GUILayout.Space(6f);
                    GUILayout.EndScrollView();
                    GUILayout.Space(8f);
                    DrawFooter();
                    GUILayout.Space(12f);
                }
                GUILayout.Space(18f);
            }
        }

        private void DrawTop()
        {
            SafetyLevel level;
            string title;
            string detail;

            switch (mode)
            {
                case Mode.Package:
                case Mode.Project:
                {
                    level = report.Level;
                    string name = mode == Mode.Package ? Path.GetFileNameWithoutExtension(report.Source) : "This project";
                    int danger = report.Count(SafetyLevel.Danger);
                    int check = report.Count(SafetyLevel.Check);
                    if (report.Error != null)
                    {
                        level = SafetyLevel.Check;
                        title = "Couldn't check " + name;
                        detail = report.Error;
                    }
                    else if (level == SafetyLevel.Danger)
                    {
                        title = mode == Mode.Package ? "Don't import this" : "Something dangerous is in this project";
                        detail = danger + (danger == 1 ? " file looks" : " files look") + " like a token logger or other malware" +
                                 (check > 0 ? ", and " + check + " more " + (check == 1 ? "needs" : "need") + " a look." : ".");
                    }
                    else if (level == SafetyLevel.Check)
                    {
                        int dlls = report.Flagged.Count(i => i.IsCompiled);
                        title = dlls > 0 ? (dlls == 1 ? "Has a DLL" : "Has " + dlls + " DLLs") + (check > dlls ? " and more to check" : string.Empty) : "Has things to check";
                        detail = "Nothing looks like a token logger, but these can run code that can't be fully checked. Keep them only if you trust where the package came from.";
                    }
                    else
                    {
                        title = "Looks clean";
                        int code = report.Items.Count;
                        detail = code == 0
                            ? "No scripts, DLLs or programs, so nothing in it can run code."
                            : "No DLLs or programs, and none of the " + code + (code == 1 ? " script" : " scripts") + " look like a token logger.";
                    }
                    if (!string.IsNullOrEmpty(headline))
                        detail = headline + " " + detail;
                    GUILayout.Label(name, dim);
                    break;
                }
                case Mode.Arrivals:
                {
                    bool danger = held.Any(h => h.IsDanger);
                    level = danger ? SafetyLevel.Danger : SafetyLevel.Check;
                    title = held.Count > 0
                        ? (danger ? "Stopped something dangerous" : "Held back " + held.Count + (held.Count == 1 ? " file" : " files") + " until you say OK")
                        : "New files to check";
                    detail = held.Count > 0
                        ? "Something new came into the project, so WPFMA-SDK moved it to " + WPFMASafety.QuarantineFolder +
                          " until you decide. Accept a file only if you trust where it came from. Deny deletes it."
                        : "These came into the project. Unity doesn't run them, but don't open them unless you trust them.";
                    break;
                }
                default:
                    level = held.Count == 0 ? SafetyLevel.Clean : SafetyLevel.Check;
                    title = held.Count == 0 ? "Nothing in quarantine" : held.Count + (held.Count == 1 ? " file" : " files") + " held back";
                    detail = "Files WPFMA-SDK moved out of the project so Unity couldn't run them. They stay here until you accept or deny them.";
                    break;
            }

            DrawBanner(level, title, detail);
        }

        private void DrawBanner(SafetyLevel level, string title, string detail)
        {
            Color color = level == SafetyLevel.Danger ? Red : level == SafetyLevel.Check ? Amber : Green;
            float width = position.width - 36f;
            float height = 34f + body.CalcHeight(new GUIContent(detail), width - 30f);
            var rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, Panel);
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, 4f, rect.height), color);
            banner.normal.textColor = color;
            GUI.Label(new Rect(rect.x + 16f, rect.y + 8f, rect.width - 24f, 22f), title, banner);
            GUI.Label(new Rect(rect.x + 16f, rect.y + 30f, rect.width - 28f, height - 32f), detail, body);
        }

        private void DrawReport()
        {
            var flagged = report.Items.Where(i => i.Shown >= SafetyLevel.Check).ToList();
            var normal = report.Items.Where(i => i.Shown < SafetyLevel.Check).ToList();

            foreach (var item in flagged)
                DrawItem(item, mode == Mode.Project);

            if (report.Level == SafetyLevel.Danger)
                DrawHelp();

            if (normal.Count > 0)
            {
                GUILayout.Space(6f);
                string label = (showNormal ? "▾ " : "▸ ") + normal.Count + (normal.Count == 1 ? " other code file looks normal" : " other code files look normal");
                if (GUILayout.Button(label, dim))
                    showNormal = !showNormal;
                if (showNormal)
                    foreach (var item in normal)
                        DrawItem(item, mode == Mode.Project);
            }

            GUILayout.Space(8f);
            GUILayout.Label("WPFMA-SDK catches the common tricks, but no checker can promise a file is safe. Only import packages from people you trust.", dim);
        }

        private void DrawArrivals()
        {
            foreach (var file in held.ToList())
            {
                if (!File.Exists(file.Stored))
                    continue;
                var item = file.Item ?? new SafetyItem
                {
                    Path = file.Original, Kind = file.Kind, Summary = file.Summary,
                    Level = file.IsDanger ? SafetyLevel.Danger : SafetyLevel.Check
                };
                DrawItem(item, false, file);
            }

            foreach (var item in noticed)
                DrawItem(item, true);

            if (held.Any(h => h.IsDanger))
                DrawHelp();
        }

        private void DrawQuarantine()
        {
            foreach (var file in held.ToList())
            {
                if (!File.Exists(file.Stored))
                    continue;
                var item = new SafetyItem
                {
                    Path = file.Original, Kind = file.Kind, Summary = file.Summary,
                    Level = file.IsDanger ? SafetyLevel.Danger : SafetyLevel.Check
                };
                DrawItem(item, false, file);
            }
        }

        /// <summary>One file: level stripe, path, kind, summary, and the reasons when opened.</summary>
        private void DrawItem(SafetyItem item, bool inProject, QuarantinedFile stored = null)
        {
            var level = item.Shown;
            Color color = level == SafetyLevel.Danger ? Red : level == SafetyLevel.Check ? Amber : DimText;
            string key = (stored != null ? stored.Stored : item.Path) ?? string.Empty;
            bool expanded = open.Contains(key);
            float width = position.width - 60f;

            string tags = item.Kind ?? string.Empty;
            if (item.IsCompiled)
                tags += item.LoadsInEditor ? " · loads in the Unity editor" : " · only in builds";
            if (item.Trusted)
                tags += " · you trusted this";
            string summary = item.Summary ?? "Nothing unusual";

            float height = 46f + rowBody.CalcHeight(new GUIContent(summary), width - 20f);
            if (expanded)
                foreach (var reason in item.Reasons)
                    height += ReasonHeight(reason, width - 20f);

            var rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(true));
            var e = Event.current;
            bool hover = rect.Contains(e.mousePosition);
            EditorGUI.DrawRect(rect, hover ? PanelHover : Panel);
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, 3f, rect.height), color);

            float buttons = DrawItemButtons(item, inProject, stored, rect);
            GUI.Label(new Rect(rect.x + 14f, rect.y + 6f, rect.width - 24f - buttons, 18f), item.Path, rowTitle);
            tag.normal.textColor = color;
            GUI.Label(new Rect(rect.x + 14f, rect.y + 24f, rect.width - 24f - buttons, 16f), tags, tag);
            float y = rect.y + 42f;
            float summaryHeight = rowBody.CalcHeight(new GUIContent(summary), width - 20f);
            GUI.Label(new Rect(rect.x + 14f, y, rect.width - 24f, summaryHeight), summary, rowBody);
            y += summaryHeight + 2f;

            if (expanded)
            {
                foreach (var reason in item.Reasons)
                {
                    float h = ReasonHeight(reason, width - 20f);
                    Color dot = reason.Level == SafetyLevel.Danger ? Red : reason.Level == SafetyLevel.Check ? Amber : DimText;
                    EditorGUI.DrawRect(new Rect(rect.x + 16f, y + 6f, 5f, 5f), dot);
                    GUI.Label(new Rect(rect.x + 28f, y, rect.width - 40f, 16f), reason.Text, rowBody);
                    if (reason.Evidence != null)
                        GUI.Label(new Rect(rect.x + 28f, y + 16f, rect.width - 40f, h - 18f), reason.Evidence, mono);
                    y += h;
                }
            }

            if (item.Reasons.Count > 0 && e.type == EventType.MouseDown && e.button == 0 && hover && e.mousePosition.x < rect.xMax - buttons)
            {
                if (!open.Remove(key))
                    open.Add(key);
                e.Use();
            }
            if (item.Reasons.Count > 0)
                EditorGUIUtility.AddCursorRect(new Rect(rect.x, rect.y, rect.width - buttons, rect.height), MouseCursor.Link);
            GUILayout.Space(4f);
        }

        private float ReasonHeight(SafetyReason reason, float width)
        {
            return 18f + (reason.Evidence != null ? mono.CalcHeight(new GUIContent(reason.Evidence), width - 20f) + 2f : 0f);
        }

        /// <summary>Per-file buttons on the right. Returns the width they take.</summary>
        private float DrawItemButtons(SafetyItem item, bool inProject, QuarantinedFile stored, Rect row)
        {
            var labels = new List<string>();
            if (stored != null)
            {
                labels.Add("Deny");
                labels.Add("Accept");
            }
            else if (inProject && item.Path != null && item.Path.StartsWith("Assets/", StringComparison.Ordinal))
            {
                if (item.Shown >= SafetyLevel.Check)
                    labels.Add("Move out");
                labels.Add("Show");
            }
            else if (inProject && item.Path != null)
                labels.Add("Show");

            float x = row.xMax - 8f;
            float used = 8f;
            foreach (var label in labels)
            {
                float w = rowBody.CalcSize(new GUIContent(label)).x + 18f;
                x -= w;
                var rect = new Rect(x, row.y + 8f, w, 22f);
                x -= 6f;
                used += w + 6f;
                if (!SmallButton(rect, label))
                    continue;

                switch (label)
                {
                    case "Deny":
                        if (EditorUtility.DisplayDialog("Deny " + Path.GetFileName(stored.Original) + "?", "It's deleted for good.", "Deny and delete", "Cancel"))
                        {
                            WPFMASafety.Delete(stored);
                            held.Remove(stored);
                        }
                        break;
                    case "Accept":
                        string warning = stored.IsDanger
                            ? "WPFMA-SDK thinks this is dangerous: " + stored.Summary + ".\n\nOnly put it back if you're sure. Unity will run it."
                            : "Unity will load it. Only put it back if you trust where it came from.";
                        if (EditorUtility.DisplayDialog("Accept " + Path.GetFileName(stored.Original) + "?", warning, stored.IsDanger ? "Accept anyway" : "Accept", "Cancel") &&
                            WPFMASafety.PutBack(stored))
                            held.Remove(stored);
                        break;
                    case "Show":
                        var asset = AssetDatabase.LoadMainAssetAtPath(item.Path);
                        if (asset != null)
                        {
                            EditorGUIUtility.PingObject(asset);
                            Selection.activeObject = asset;
                        }
                        else
                            EditorUtility.RevealInFinder(Path.Combine(WPFMASafety.ProjectRoot, item.Path));
                        break;
                    case "Move out":
                        MoveOut(item);
                        break;
                }
                GUIUtility.ExitGUI();
            }
            return used;
        }

        private void MoveOut(SafetyItem item)
        {
            if (!EditorUtility.DisplayDialog("Move " + Path.GetFileName(item.Path) + " out of the project?",
                    "It goes to " + WPFMASafety.QuarantineFolder + ", where Unity can't run it. You can put it back from Settings → Package safety.", "Move it", "Cancel"))
                return;

            string from = Path.Combine(WPFMASafety.ProjectRoot, item.Path);
            string to = Path.Combine(WPFMASafety.QuarantineRoot, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"), item.Path);
            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(to));
                File.Move(from, to);
                if (File.Exists(from + ".meta"))
                    File.Move(from + ".meta", to + ".meta");
                new QuarantinedFile { Original = item.Path, Stored = to, Item = item }.Save();
                report.Items.Remove(item);
                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                EditorUtility.DisplayDialog("Package safety", "Couldn't move it: " + e.Message, "OK");
            }
        }

        /// <summary>
        /// Puts every held file back in one go. Files it thinks are dangerous (token loggers and the like) only go
        /// back if you pick that on purpose; by default it's just the ordinary ones.
        /// </summary>
        private void AcceptAll()
        {
            var danger = held.Where(h => h.IsDanger).ToList();
            var ordinary = held.Where(h => !h.IsDanger).ToList();
            List<QuarantinedFile> chosen;

            if (danger.Count == 0)
            {
                if (!EditorUtility.DisplayDialog("Accept all " + held.Count + " files?",
                        "Unity will load them all. Only do this if you trust where they came from.", "Accept all", "Cancel"))
                    GUIUtility.ExitGUI();
                chosen = ordinary;
            }
            else
            {
                int pick = EditorUtility.DisplayDialogComplex("Accept all?",
                    danger.Count + " of these " + held.Count + " files look dangerous (" + danger[0].Summary + (danger.Count > 1 ? ", and more" : string.Empty) +
                    "). Unity runs whatever you put back.\n\nPut back only the " + ordinary.Count + " ordinary file(s), or all of them?",
                    "Only the ordinary ones", "Cancel", "All, dangerous too");
                if (pick == 1 || (pick == 0 && ordinary.Count == 0))
                    GUIUtility.ExitGUI();
                chosen = pick == 2 ? held.ToList() : ordinary;
            }

            // Whatever went back is no longer in the quarantine folder; the rest (say, a file already there) stays listed.
            WPFMASafety.Accept(chosen);
            held.RemoveAll(f => !File.Exists(f.Stored));
            Repaint();
            GUIUtility.ExitGUI();
        }

        private void DrawHelp()
        {
            GUILayout.Space(6f);
            const string text =
                "If you already imported or opened something like this:\n" +
                "•  Change your Discord password. That logs out every session and makes a stolen token useless. Then turn on 2FA.\n" +
                "•  Change the passwords saved in your browser, email first.\n" +
                "•  Run a full scan: Windows Security → Virus & threat protection → Scan options → Full scan.\n" +
                "•  Warn whoever you got it from, and the server it was posted in.";
            float height = rowBody.CalcHeight(new GUIContent(text), position.width - 70f) + 16f;
            var rect = GUILayoutUtility.GetRect(1f, height, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, RedDim);
            EditorGUI.DrawRect(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f), Panel);
            GUI.Label(new Rect(rect.x + 12f, rect.y + 8f, rect.width - 24f, height - 12f), text, rowBody);
            GUILayout.Space(4f);
        }

        private void DrawFooter()
        {
            using (new GUILayout.HorizontalScope())
            {
                switch (mode)
                {
                    case Mode.Package:
                    {
                        bool flagged = report.Flagged.Any();
                        bool danger = report.Level == SafetyLevel.Danger;
                        if (BigButton("Cancel", 110f, false))
                        {
                            Pick(WPFMASafety.Choice.Cancel);
                            Close();
                            GUIUtility.ExitGUI();
                        }
                        GUILayout.FlexibleSpace();
                        if (report.Error == null && flagged && BigButton(report.Flagged.All(i => i.IsCompiled) ? "Import without the DLLs" : "Import without these files", 210f, !danger))
                        {
                            Pick(WPFMASafety.Choice.ImportWithout);
                            Close();
                            GUIUtility.ExitGUI();
                        }
                        GUILayout.Space(8f);
                        if (BigButton(danger ? "Import anyway" : "Import", danger ? 140f : 110f, false, danger))
                        {
                            if (!danger || EditorUtility.DisplayDialog("Import a dangerous package?",
                                    "WPFMA-SDK thinks this package has a token logger or other malware in it. Unity will run it as soon as it's imported.",
                                    "Import anyway", "Cancel"))
                            {
                                Pick(WPFMASafety.Choice.Import);
                                Close();
                            }
                            GUIUtility.ExitGUI();
                        }
                        break;
                    }
                    case Mode.Project:
                        if (BigButton("Check again", 130f, false))
                        {
                            report = WPFMASafety.CheckProject();
                            GUIUtility.ExitGUI();
                        }
                        GUILayout.FlexibleSpace();
                        if (BigButton("Done", 110f, true))
                            Close();
                        break;
                    default:
                        if (BigButton("Open quarantine folder", 190f, false))
                            WPFMASafety.OpenQuarantineFolder();
                        GUILayout.FlexibleSpace();
                        if (held.Count > 1)
                        {
                            if (BigButton("Accept all", 110f, false))
                                AcceptAll();
                            GUILayout.Space(8f);
                        }
                        if (BigButton("Done", 110f, true))
                            Close();
                        break;
                }
            }
        }

        // ---- Bits -------------------------------------------------------------------------------------------------------

        private bool BigButton(string label, float width, bool primary, bool risky = false)
        {
            var rect = GUILayoutUtility.GetRect(width, 32f, GUILayout.Width(width));
            var e = Event.current;
            bool hover = rect.Contains(e.mousePosition);
            Color fill = risky ? (hover ? Red : RedDim) : primary ? (hover ? Accent : AccentDim) : (hover ? AccentDim : Border);
            EditorGUI.DrawRect(rect, fill);
            if (!primary && !risky)
                EditorGUI.DrawRect(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f), hover ? PanelHover : Background);
            buttonText.normal.textColor = (primary || risky) && hover ? AccentText : TitleText;
            GUI.Label(rect, label, buttonText);
            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            if (e.type == EventType.MouseDown && e.button == 0 && hover)
            {
                e.Use();
                return true;
            }
            return false;
        }

        private bool SmallButton(Rect rect, string label)
        {
            var e = Event.current;
            bool hover = rect.Contains(e.mousePosition);
            EditorGUI.DrawRect(rect, hover ? AccentDim : Border);
            EditorGUI.DrawRect(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f), hover ? PanelHover : Background);
            GUI.Label(rect, label, new GUIStyle(rowBody) { alignment = TextAnchor.MiddleCenter, wordWrap = false });
            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            if (e.type == EventType.MouseDown && e.button == 0 && hover)
            {
                e.Use();
                return true;
            }
            return false;
        }

        private void Styles()
        {
            if (titleStyle != null)
                return;
            titleStyle = new GUIStyle(EditorStyles.boldLabel) { fontSize = 17, normal = { textColor = TitleText } };
            banner = new GUIStyle(EditorStyles.boldLabel) { fontSize = 16 };
            body = new GUIStyle(EditorStyles.label) { fontSize = 12, wordWrap = true, normal = { textColor = BodyText } };
            dim = new GUIStyle(EditorStyles.label) { fontSize = 11, wordWrap = true, normal = { textColor = DimText } };
            rowTitle = new GUIStyle(EditorStyles.boldLabel) { fontSize = 12, clipping = TextClipping.Clip, normal = { textColor = TitleText } };
            rowBody = new GUIStyle(EditorStyles.label) { fontSize = 11, wordWrap = true, normal = { textColor = BodyText } };
            tag = new GUIStyle(EditorStyles.miniLabel) { fontSize = 10, clipping = TextClipping.Clip };
            mono = new GUIStyle(EditorStyles.miniLabel) { fontSize = 10, wordWrap = true, normal = { textColor = DimText } };
            var font = Font.CreateDynamicFontFromOSFont(new[] { "Consolas", "Menlo", "DejaVu Sans Mono" }, 10);
            if (font != null)
                mono.font = font;
            buttonText = new GUIStyle(EditorStyles.boldLabel) { fontSize = 12, alignment = TextAnchor.MiddleCenter };
        }
    }
}
#endif
