// 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 System.Reflection;
using WPFMA.Vrca;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    public sealed class WPFMAWindow : EditorWindow
    {
        private const string WindowTitle = "WPFMA Panel";
        private const string DefaultLogoPath = "Assets/WPFMA-SDK/IMG/label_import_1.png";
        private const string RipperLogoPath = "Assets/WPFMA-SDK/IMG/label_ripper_1.png";
        private const string InfoLogoPath = "Assets/WPFMA-SDK/IMG/label_info_1.png";
        private const string SettingsLogoPath = "Assets/WPFMA-SDK/IMG/label_settings.png";
        private const string ToolsLogoPath = "Assets/WPFMA-SDK/IMG/label_tools.png";
        private const string TeamLogoPath = "Assets/WPFMA-SDK/IMG/teams_banner.png";
        private static Color PanelBackground => WPFMATheme.Shift(new Color(17f / 255f, 20f / 255f, 25f / 255f));
        private static Color TabBackground => WPFMATheme.Shift(new Color(33f / 255f, 38f / 255f, 46f / 255f));
        private static Color AccentBlue => WPFMATheme.Shift(new Color(126f / 255f, 182f / 255f, 222f / 255f));
        private static Color AccentText => WPFMATheme.Shift(new Color(14f / 255f, 24f / 255f, 33f / 255f));
        private static Color SurfaceBackground => WPFMATheme.Shift(new Color(21f / 255f, 25f / 255f, 31f / 255f));
        private static Color RowBackground => WPFMATheme.Shift(new Color(26f / 255f, 31f / 255f, 38f / 255f));

        private static Color ToolbarBackground => WPFMATheme.Shift(new Color(24f / 255f, 29f / 255f, 37f / 255f));
        private static Color ToolbarEdge => WPFMATheme.Shift(new Color(11f / 255f, 14f / 255f, 18f / 255f));
        private static Color RowOdd => WPFMATheme.Shift(new Color(21f / 255f, 26f / 255f, 33f / 255f));
        private static Color RowEven => WPFMATheme.Shift(new Color(18f / 255f, 22f / 255f, 28f / 255f));
        private static Color RowSelected => WPFMATheme.Shift(new Color(40f / 255f, 66f / 255f, 88f / 255f));
        private static Color Separator => WPFMATheme.Shift(new Color(33f / 255f, 38f / 255f, 46f / 255f));
        private static Color MetaText => WPFMATheme.Shift(new Color(143f / 255f, 163f / 255f, 181f / 255f));
        private static Color DimText => WPFMATheme.Shift(new Color(110f / 255f, 124f / 255f, 139f / 255f));
        private static Color FaintText => WPFMATheme.Shift(new Color(78f / 255f, 91f / 255f, 105f / 255f));
        private static readonly Color OkGreen = new Color(93f / 255f, 202f / 255f, 165f / 255f);
        private static readonly Color WarnAmber = new Color(239f / 255f, 159f / 255f, 39f / 255f);
        private static readonly string[] BundledCredits =
        {
            "Avatar Compressor (LAC) — Limitex (bundled copy, MIT)",
            "Modular Avatar — bd_ (bundled copy, MIT)",
            "NDMF — bd_ and contributors (bundled copy, MIT)",
            "EasyQuestSwitch — Jordo (bundled copy, BSD-3-Clause + no-fee clause)",
            "Gesture Manager — BlackStartx (bundled, modified copy, MIT)",
            "FACS Utilities — FACS01 (bundled copy, OSL-3.0)",
            "Gesture Manager — BlackStartx (extended with Move & Jump)",
            "VRChat SDK — VRChat Inc.",
            "VRCFury — VRCFury",
            "Poiyomi Toon and Thry Editor — Poiyomi, Thryrallo",
            "lilToon — lilxyzw",
            "d4rkAvatarOptimizer — d4rkpl4y3r",
            "FBX Exporter — Unity Technologies",
            "QHierarchy"
        };

        private static readonly string[] ReferenceCredits =
        {
            "SARS — Dean2k",
            "ARC, and AssetsTools.NET — nesrak1",
            "AssetRipper (used to check recovered animation against)"
        };

        private const string ImportFolderPath = "Assets/WPFMA-SDK/Import";
        private const string FbxExportFolder = "Assets/WPFMA-SDK/Fbxs";
        private const string FbxEditorAssemblyName = "Unity.Formats.Fbx.Editor";
        private const string FbxModelExporterTypeName = "UnityEditor.Formats.Fbx.Exporter.ModelExporter";

        internal enum Tab
        {
            Importer,
            Ripper,
            Info,
            Settings,
            Tools,
            Team
        }

        private Tab activeTab = Tab.Importer;
        private Vector2 scrollPosition;
        private Texture2D logo;
        [NonSerialized] private GUIStyle accentButtonStyle;
        [NonSerialized] private GUIStyle tabButtonStyle;
        [NonSerialized] private GUIStyle activeTabButtonStyle;
        [NonSerialized] private GUIStyle importerSectionStyle;
        [NonSerialized] private GUIStyle importerTitleStyle;
        [NonSerialized] private GUIStyle importerPathStyle;
        [NonSerialized] private GUIStyle importerHintStyle;
        [NonSerialized] private GUIStyle importerRowStyle;
        [NonSerialized] private GUIStyle importerRowLabelStyle;
        private readonly RipperTabState ripperTabState = new RipperTabState();
        private string fbxExportName = "ExportedModel";
        private bool fbxSettingsExpanded;
        private bool fbxHumanoid;
        private Transform fbxAnimationSource;
        private Transform fbxAnimationDestination;
        private Vector2 toolsScrollPosition;
        private GameObject packageAvatar;
        private bool packageIncludeScene = true;
        private WPFMAPackageBuilder.Plan packagePlan;
        private string packageStatus;
        private readonly WPFMAVpmRepository vpmRepository = new WPFMAVpmRepository();
        private string vpmRepositoryUrl = "https://vcc.vrcfury.com";
        private List<WPFMAVpmPackage> vpmPackages = new List<WPFMAVpmPackage>();
        private List<WPFMAVpmPackage> cachedVpmPackages = new List<WPFMAVpmPackage>();
        private string vpmStatus;
        private bool vpmBusy;
        private int vpmBatchIndex = -1;
        private string importerFilter = string.Empty;
        private string archiveCode = string.Empty;
        private readonly HashSet<string> importerSelection = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        [NonSerialized] private GUIStyle importerToolbarButtonStyle;
        [NonSerialized] private GUIStyle importerRowNameStyle;
        [NonSerialized] private GUIStyle importerMetaStyle;
        [NonSerialized] private GUIStyle importerOutlineButtonStyle;
        private bool vpmRepositoryExpanded = true;
        private readonly List<string> importQueue = new List<string>();
        private bool importQueueRunning;

        [MenuItem("WPFMA-SDK/Open WPFMA-SDK", false, 0)]
        public static void Open()
        {
            var window = GetWindow<WPFMAWindow>();
            window.titleContent = new GUIContent(WindowTitle);
            window.minSize = new Vector2(420f, 300f);
            window.Show();
        }

        [MenuItem("Window/WPFMA-SDK/Control Panel", false, 0)]
        private static void OpenFromWindowMenu()
        {
            Open();
        }

        private void OnEnable()
        {
            titleContent = new GUIContent(WindowTitle);
            Directory.CreateDirectory(ImportFolderPath);
            logo = AssetDatabase.LoadAssetAtPath<Texture2D>(DefaultLogoPath);
            cachedVpmPackages = WPFMAVpmRepository.LoadCachedPackages();
            WPFMADiscordPresence.SetPanelState("Importer");
        }

        private void OnDisable()
        {
            vpmRepository.Cancel();

            WPFMAQuestSwitchHost.Release();
            WPFMA.Team.TeamLook.ReleasePreview();
        }

        private void OnGUI()
        {
            EnsureVisualStyles();
            EditorGUI.DrawRect(new Rect(0f, 0f, position.width, position.height), PanelBackground);
            DrawHeader();
            DrawTabs();

            using (var scroll = new EditorGUILayout.ScrollViewScope(scrollPosition))
            {
                scrollPosition = scroll.scrollPosition;
                EditorGUILayout.Space(12f);
                if (activeTab == Tab.Importer)
                    DrawImporterTab();
                else if (activeTab == Tab.Ripper)
                    DrawRipperTab();
                else if (activeTab == Tab.Info)
                    DrawInfoTab();
                else if (activeTab == Tab.Tools)
                    DrawToolsTab();
                else if (activeTab == Tab.Team)
                    WPFMA.Team.TeamPanel.Draw(importerSectionStyle, importerHintStyle);
                else
                    DrawSettingsTab();
            }
        }

        private int stylesTheme = -1;

        private void EnsureVisualStyles()
        {
            if (stylesTheme != WPFMATheme.Version)
            {
                stylesTheme = WPFMATheme.Version;
                accentButtonStyle = null;
            }
            if (accentButtonStyle != null && accentButtonStyle.normal.background != null &&
                tabButtonStyle != null && activeTabButtonStyle != null && importerSectionStyle != null &&
                importerTitleStyle != null && importerPathStyle != null && importerHintStyle != null &&
                importerRowStyle != null &&
                importerRowLabelStyle != null && importerToolbarButtonStyle != null &&
                importerRowNameStyle != null && importerMetaStyle != null && importerOutlineButtonStyle != null)
                return;

            accentButtonStyle = CreateFlatButtonStyle(AccentBlue, AccentText);
            tabButtonStyle = CreateFlatButtonStyle(TabBackground, new Color(0.85f, 0.85f, 0.85f));
            activeTabButtonStyle = CreateFlatButtonStyle(AccentBlue, AccentText);
            importerSectionStyle = CreateBoxStyle(SurfaceBackground, new RectOffset(12, 12, 10, 10), new RectOffset(1, 1, 1, 1));
            importerTitleStyle = new GUIStyle(EditorStyles.boldLabel)
            {
                fontSize = 16,
                normal = { textColor = new Color(0.85f, 0.85f, 0.85f) },
                hover = { textColor = new Color(0.95f, 0.95f, 0.95f) },
                active = { textColor = new Color(1f, 1f, 1f) },
                alignment = TextAnchor.MiddleLeft,
                padding = new RectOffset(0, 0, 2, 2),
                margin = new RectOffset(0, 0, 0, 0)
            };
            importerPathStyle = new GUIStyle(EditorStyles.miniLabel)
            {
                normal = { textColor = new Color(0.62f, 0.62f, 0.62f) },
                hover = { textColor = new Color(0.78f, 0.78f, 0.78f) },
                active = { textColor = new Color(0.82f, 0.82f, 0.82f) }
            };
            importerHintStyle = new GUIStyle(importerPathStyle)
            {
                wordWrap = true,
                margin = new RectOffset(2, 2, 0, 4)
            };
            importerRowStyle = CreateBoxStyle(RowBackground, new RectOffset(10, 10, 6, 6), new RectOffset(1, 1, 1, 1));
            importerRowLabelStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 13,
                normal = { textColor = new Color(0.75f, 0.75f, 0.75f) },
                hover = { textColor = new Color(0.92f, 0.92f, 0.92f) },
                active = { textColor = new Color(1f, 1f, 1f) },
                alignment = TextAnchor.MiddleLeft
            };
            importerToolbarButtonStyle = CreateFlatButtonStyle(WPFMATheme.Shift(new Color(31f / 255f, 37f / 255f, 46f / 255f)), WPFMATheme.Shift(new Color(0.79f, 0.83f, 0.87f)));
            importerToolbarButtonStyle.fontSize = 12;
            importerToolbarButtonStyle.padding = new RectOffset(9, 9, 2, 2);
            importerOutlineButtonStyle = CreateFlatButtonStyle(WPFMATheme.Shift(new Color(31f / 255f, 37f / 255f, 46f / 255f)), WPFMATheme.Shift(new Color(0.79f, 0.83f, 0.87f)));
            importerOutlineButtonStyle.fontSize = 12;
            importerRowNameStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 12,
                normal = { textColor = WPFMATheme.Shift(new Color(0.79f, 0.83f, 0.87f)) },
                alignment = TextAnchor.MiddleLeft,
                padding = new RectOffset(0, 0, 0, 0)
            };
            importerMetaStyle = new GUIStyle(EditorStyles.label)
            {
                fontSize = 11,
                normal = { textColor = MetaText },
                alignment = TextAnchor.MiddleRight,
                padding = new RectOffset(0, 0, 0, 0)
            };
        }

        private void DrawHeader()
        {
            var headerTexture = GetHeaderTexture();
            if (headerTexture != null)
            {
                float targetWidth = Mathf.Min(headerTexture.width, position.width - 20f);
                float scale = targetWidth / headerTexture.width;
                float targetHeight = headerTexture.height * scale;

                var imageRect = GUILayoutUtility.GetRect(targetWidth, targetHeight, GUILayout.ExpandWidth(false));
                imageRect.x = (position.width - targetWidth) * 0.5f;
                EditorGUI.DrawRect(imageRect, PanelBackground);
                GUI.DrawTexture(imageRect, headerTexture, ScaleMode.ScaleToFit, true);
            }
        }

        private Texture2D GetHeaderTexture()
        {
            var path = activeTab switch
            {
                Tab.Importer => DefaultLogoPath,
                Tab.Ripper => RipperLogoPath,
                Tab.Info => InfoLogoPath,
                Tab.Settings => SettingsLogoPath,
                Tab.Tools => ToolsLogoPath,
                Tab.Team => TeamLogoPath,
                _ => DefaultLogoPath
            };

            return WPFMATheme.Banner(path) ?? logo;
        }

        private const string HideExporterKey = "WPFMA.Settings.HideExporter";

        /// <summary>
        /// The Exporter tab (and its Welcome card) is off until someone turns it on in Settings > Exporter
        /// and agrees to use it only on models that are theirs or that they have permission to use.
        /// </summary>
        internal static bool ExporterHidden
        {
            get { return EditorPrefs.GetBool(HideExporterKey, true); }
            set { EditorPrefs.SetBool(HideExporterKey, value); }
        }

        private const string ExporterTerms =
            "For your own models, or ones the creator has given you permission to use. " +
            "Don't re-upload, share or sell anyone else's work.";

        /// <summary>Asks before the Exporter is turned on. True when they agreed.</summary>
        private static bool AgreeToExporter()
        {
            return EditorUtility.DisplayDialog("Turn on the Exporter?",
                "The Exporter is for backing up and working on avatars and worlds that are yours, or that the creator " +
                "has given you permission to use.\n\n" +
                "Don't use it to take, re-upload, share or sell other people's work. That breaks VRChat's Terms of Service " +
                "and the creator's license, and can get your account banned.\n\n" +
                "You're responsible for how you use it.",
                "I understand, turn it on", "Cancel");
        }

        private void DrawTabs()
        {
            if ((activeTab == Tab.Ripper && ExporterHidden) ||
                (activeTab == Tab.Team && TeamHidden && WPFMA.Team.TeamSession.State == WPFMA.Team.TeamState.Idle))
                activeTab = Tab.Importer;
            EditorGUILayout.Space(6f);
            using (new EditorGUILayout.HorizontalScope())
            {
                DrawTabButton(Tab.Importer, "Importer");
                if (!ExporterHidden)
                    DrawTabButton(Tab.Ripper, "Exporter");
                DrawTabButton(Tab.Tools, "Tools");
                DrawTabButton(Tab.Info, "Info");
                if (!TeamHidden || WPFMA.Team.TeamSession.State != WPFMA.Team.TeamState.Idle)
                    DrawTabButton(Tab.Team, WPFMA.Team.TeamSession.Unread > 0 ? "Team (" + WPFMA.Team.TeamSession.Unread + ")" :
                    WPFMA.Team.TeamSession.State == WPFMA.Team.TeamState.Connected ? "Team ●" : "Team");
                DrawTabButton(Tab.Settings, "Settings");
            }
        }

        private void DrawTabButton(Tab tab, string label)
        {
            var style = activeTab == tab ? activeTabButtonStyle : tabButtonStyle;
            if (GUILayout.Button(label, style, GUILayout.Height(30f)))
            {
                activeTab = tab;
                WPFMADiscordPresence.SetPanelState(label);
            }
        }

        private void DrawImporterTab()
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(importerSectionStyle);

            try
            {
                var packages = GetFilteredPackages(out int totalCount, out long totalBytes);
                DrawImporterToolbar();
                DrawImporterSummary(totalCount, totalBytes);
                DrawImporterList(packages);
                DrawImporterStatusBar(packages);

                DrawVpmRepository();
            }
            finally
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
            }
        }

        private void DrawVpmRepository()
        {
            EditorGUILayout.Space(10f);

            var header = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(header, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(header.x, header.y, header.width, 1f), ToolbarEdge);

            if (GUI.Button(new Rect(header.x, header.y, header.width, header.height), GUIContent.none, GUIStyle.none))
                vpmRepositoryExpanded = !vpmRepositoryExpanded;

            GUI.Label(new Rect(header.x + 6f, header.y, 16f, header.height), vpmRepositoryExpanded ? "\u25BE" : "\u25B8",
                new GUIStyle(importerRowNameStyle) { normal = { textColor = DimText } });
            GUI.Label(new Rect(header.x + 22f, header.y, 200f, header.height), "VPM repository",
                new GUIStyle(importerRowNameStyle) { normal = { textColor = AccentBlue } });

            cachedVpmPackages = WPFMAVpmRepository.LoadCachedPackages();
            GUI.Label(new Rect(header.xMax - ScrollbarGutter - 204f, header.y, 200f, header.height),
                vpmPackages.Count + " fetched, " + cachedVpmPackages.Count + " cached",
                new GUIStyle(importerMetaStyle) { normal = { textColor = FaintText } });

            if (!vpmRepositoryExpanded)
                return;

            DrawVpmToolbar();

            if (!string.IsNullOrEmpty(vpmStatus))
            {
                var statusRect = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(statusRect, RowEven);
                GUI.Label(new Rect(statusRect.x + 8f, statusRect.y, statusRect.width - 16f, statusRect.height), vpmStatus,
                    new GUIStyle(importerRowNameStyle)
                    {
                        fontSize = 11,
                        normal = { textColor = vpmBusy ? AccentBlue : DimText }
                    });
            }

            DrawVpmSectionLabel("Fetched packages");
            if (vpmPackages.Count == 0)
                DrawVpmEmptyRow("Nothing fetched yet. Enter a repository URL and press Fetch.");
            else
                for (int i = 0; i < vpmPackages.Count; i++)
                    DrawVpmRow(vpmPackages[i], i, true);

            DrawVpmSectionLabel("Cached packages");
            if (cachedVpmPackages.Count == 0)
                DrawVpmEmptyRow("Nothing cached yet. Cache a fetched package to keep it here permanently.");
            else
                for (int i = 0; i < cachedVpmPackages.Count; i++)
                    DrawVpmRow(cachedVpmPackages[i], i, false);
        }

        private void DrawVpmToolbar()
        {
            var rect = GUILayoutUtility.GetRect(0f, 28f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.yMax - 1f, rect.width, 1f), ToolbarEdge);

            float top = rect.y + 4f;
            const float height = 20f;

            using (new EditorGUI.DisabledScope(vpmBusy))
            {
                float cacheWidth = ButtonWidth(importerToolbarButtonStyle, "Cache all");
                float fetchWidth = ButtonWidth(importerToolbarButtonStyle, "Fetch");
                var cacheRect = new Rect(rect.xMax - ScrollbarGutter - cacheWidth - 4f, top, cacheWidth, height);
                var fetchRect = new Rect(cacheRect.x - fetchWidth - 5f, top, fetchWidth, height);

                var urlRect = new Rect(rect.x + 6f, top, Mathf.Max(80f, fetchRect.x - rect.x - 12f), height);
                vpmRepositoryUrl = EditorGUI.TextField(urlRect, vpmRepositoryUrl);

                if (GUI.Button(fetchRect, "Fetch", importerToolbarButtonStyle))
                    FetchVpmRepository();

                using (new EditorGUI.DisabledScope(vpmPackages.Count == 0))
                {
                    if (GUI.Button(cacheRect, "Cache all", importerToolbarButtonStyle))
                        CacheNextVpmPackage(0);
                }
            }
        }

        private void DrawVpmSectionLabel(string label)
        {
            var rect = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), Separator);
            GUI.Label(new Rect(rect.x + 8f, rect.y, rect.width - 16f, rect.height), label,
                new GUIStyle(importerRowNameStyle) { fontSize = 11, normal = { textColor = FaintText } });
        }

        private void DrawVpmEmptyRow(string message)
        {
            var rect = GUILayoutUtility.GetRect(0f, 22f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, RowEven);
            GUI.Label(new Rect(rect.x + 8f, rect.y, rect.width - 16f, rect.height), message,
                new GUIStyle(importerRowNameStyle) { fontSize = 11, normal = { textColor = DimText } });
        }

        private void DrawVpmRow(WPFMAVpmPackage package, int index, bool fetched)
        {
            var row = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(row, index % 2 == 0 ? RowOdd : RowEven);

            float right = row.xMax - ScrollbarGutter - 4f;
            bool cached = package.IsCached;

            using (new EditorGUI.DisabledScope(vpmBusy))
            {
                float installWidth = ButtonWidth(importerOutlineButtonStyle, "Install");
                var installRect = new Rect(right - installWidth, row.y + 3f, installWidth, 18f);

                using (new EditorGUI.DisabledScope(!cached))
                {
                    var installLabel = new GUIContent("Install",
                        cached
                            ? "Unpack this package into Packages/ and add it to the manifest."
                            : "Cache it first - there is no downloaded archive to install yet.");

                    if (GUI.Button(installRect, installLabel, cached ? accentButtonStyle : importerOutlineButtonStyle))
                        InstallVpmPackage(package);
                }

                right = installRect.x - 5f;

                if (fetched)
                {
                    if (cached)
                    {
                        GUI.Label(new Rect(right - 60f, row.y, 56f, row.height), "cached",
                            new GUIStyle(importerMetaStyle) { normal = { textColor = OkGreen } });
                        right -= 64f;
                    }
                    else
                    {
                        float cacheWidth = ButtonWidth(importerOutlineButtonStyle, "Cache");
                        var cacheRect = new Rect(right - cacheWidth, row.y + 3f, cacheWidth, 18f);
                        if (GUI.Button(cacheRect, "Cache", importerOutlineButtonStyle))
                            CacheVpmPackage(package);

                        right = cacheRect.x - 5f;
                    }
                }
            }

            GUI.Label(new Rect(right - 76f, row.y, 72f, row.height), package.Version,
                new GUIStyle(importerMetaStyle) { normal = { textColor = MetaText } });

            var nameRect = new Rect(row.x + 8f, row.y, Mathf.Max(60f, right - row.x - 86f), row.height);
            GUI.Label(nameRect, new GUIContent(package.Name, package.CachePath ?? package.DownloadUrl), importerRowNameStyle);
        }

        private void FetchVpmRepository()
        {
            if (!Uri.TryCreate(vpmRepositoryUrl.Trim(), UriKind.Absolute, out var uri) ||
                (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
            {
                vpmStatus = "Enter a valid http:// or https:// repository URL.";
                return;
            }

            vpmBusy = true;
            vpmStatus = "Fetching repository metadata...";
            WPFMADiscordPresence.SetBusyState("Fetching VPM repository", 20d);
            vpmPackages.Clear();
            vpmRepository.Fetch(uri.ToString(), (packages, error) =>
            {
                vpmBusy = false;
                if (!string.IsNullOrEmpty(error))
                {
                    vpmStatus = "Fetch failed: " + error;
                    WPFMADiscordPresence.SetBusyState("VPM fetch failed", 10d);
                    return;
                }

                vpmPackages = packages;
                cachedVpmPackages = WPFMAVpmRepository.LoadCachedPackages();
                vpmStatus = packages.Count + " latest package(s) found.";
                WPFMADiscordPresence.SetBusyState("VPM repository ready", 10d);
                Repaint();
            });
        }

        private void CacheVpmPackage(WPFMAVpmPackage package)
        {
            vpmBusy = true;
            vpmStatus = "Caching " + package.Name + "...";
            WPFMADiscordPresence.SetBusyState("Caching VPM package: " + package.Name, 25d);
            vpmRepository.Download(package, (path, error) =>
            {
                vpmBusy = false;
                cachedVpmPackages = WPFMAVpmRepository.LoadCachedPackages();
                vpmStatus = string.IsNullOrEmpty(error) ? "Cached " + package.Name + " " + package.Version + "." : "Cache failed: " + error;
                WPFMADiscordPresence.SetBusyState(string.IsNullOrEmpty(error) ? "Cached: " + package.Name : "Cache failed: " + package.Name, 10d);
                Repaint();
            });
        }

        private void CacheNextVpmPackage(int index)
        {
            if (index >= vpmPackages.Count)
            {
                vpmBusy = false;
                vpmBatchIndex = -1;
                vpmStatus = "Cached all latest packages.";
                WPFMADiscordPresence.SetBusyState("VPM cache complete", 10d);
                Repaint();
                return;
            }

            vpmBusy = true;
            vpmBatchIndex = index;
            var package = vpmPackages[index];
            if (package.IsCached)
            {
                CacheNextVpmPackage(index + 1);
                return;
            }

            vpmStatus = "Caching " + package.Name + " (" + (index + 1) + "/" + vpmPackages.Count + ")...";
            WPFMADiscordPresence.SetBusyState("Caching VPM package: " + package.Name + " (" + (index + 1) + "/" + vpmPackages.Count + ")", 25d);
            vpmRepository.Download(package, (path, error) =>
            {
                if (!string.IsNullOrEmpty(error))
                {
                    vpmBusy = false;
                    vpmBatchIndex = -1;
                    vpmStatus = "Cache failed for " + package.Name + ": " + error;
                    WPFMADiscordPresence.SetBusyState("VPM cache failed: " + package.Name, 10d);
                    Repaint();
                    return;
                }
                CacheNextVpmPackage(index + 1);
            });
        }

        private void InstallVpmPackage(WPFMAVpmPackage package)
        {
            try
            {
                vpmBusy = true;
                vpmStatus = "Installing " + package.Name + "...";
                WPFMADiscordPresence.SetBusyState("Installing VPM package: " + package.Name, 30d);
                WPFMAVpmRepository.Install(package);
                cachedVpmPackages = WPFMAVpmRepository.LoadCachedPackages();
                vpmStatus = "Installed " + package.Name + " " + package.Version + ".";
                WPFMADiscordPresence.SetBusyState("Installed: " + package.Name, 10d);
            }
            catch (Exception exception)
            {
                vpmStatus = "Install failed: " + exception.Message;

                Debug.LogError("[WPFMA-SDK] Could not install VPM package '" + package.Name + "' " +
                               package.Version + " from " + package.CachePath + ":\n" + exception);

                WPFMADiscordPresence.SetBusyState("VPM install failed: " + package.Name, 10d);
            }
            finally
            {
                vpmBusy = false;
                Repaint();
            }
        }

        private static GUIStyle CreateBoxStyle(Color fillColor, RectOffset padding, RectOffset border)
        {
            var background = new Texture2D(1, 1);
            background.SetPixel(0, 0, fillColor);
            background.Apply();
            background.hideFlags = HideFlags.HideAndDontSave;

            var style = new GUIStyle(GUI.skin.box)
            {
                normal = { background = background },
                border = border,
                padding = padding,
                margin = new RectOffset(0, 0, 0, 0)
            };

            return style;
        }

        private void EnqueuePackageImport(string packagePath)
        {
            if (string.IsNullOrEmpty(packagePath) || importQueue.Contains(packagePath))
                return;

            importQueue.Add(packagePath);
            Repaint();
        }

        private void ClearImportQueue()
        {
            importQueue.Clear();
            importQueueRunning = false;
            WPFMADiscordPresence.ClearBusyState();
            Repaint();
        }

        private void ImportPackageNow(string packagePath)
        {
            string packageName = Path.GetFileNameWithoutExtension(packagePath);
            WPFMADiscordPresence.SetBusyState("Importing: " + packageName);
            try
            {
                // Checked for DLLs and token loggers first.
                WPFMASafety.ImportChecked(packagePath, true, started =>
                {
                    if (started)
                        EditorPrefs.SetString(ImportedPrefPrefix + packageName, DateTime.Now.ToString("s"));
                });
            }
            finally
            {
                WPFMADiscordPresence.ClearBusyState();
            }
        }

        private void ImportQueuedPackages()
        {
            if (importQueueRunning || importQueue.Count == 0)
                return;

            importQueueRunning = true;
            ProcessNextQueuedImport();
        }

        private void ProcessNextQueuedImport()
        {
            if (importQueue.Count == 0)
            {
                importQueueRunning = false;
                WPFMADiscordPresence.ClearBusyState();
                Repaint();
                return;
            }

            var nextPackage = importQueue[0];
            importQueue.RemoveAt(0);

            string packageName = Path.GetFileNameWithoutExtension(nextPackage);
            WPFMADiscordPresence.SetBusyState("Importing queue: " + packageName);
            WPFMASafety.ImportChecked(nextPackage, true, null);

            EditorApplication.delayCall += () =>
            {
                if (importQueue.Count == 0)
                {
                    importQueueRunning = false;
                    WPFMADiscordPresence.ClearBusyState();
                    Repaint();
                    return;
                }

                ProcessNextQueuedImport();
            };
        }

        private bool DrawActionButton(string label, float height, params GUILayoutOption[] options)
        {
            var layoutOptions = new GUILayoutOption[options.Length + 1];
            layoutOptions[0] = GUILayout.Height(height);
            options.CopyTo(layoutOptions, 1);
            return GUILayout.Button(label, accentButtonStyle, layoutOptions);
        }

        private static GUIStyle CreateFlatButtonStyle(Color color, Color textColor)
        {
            var texture = new Texture2D(1, 1);
            texture.SetPixel(0, 0, color);
            texture.Apply();
            texture.hideFlags = HideFlags.HideAndDontSave;

            var style = new GUIStyle(GUI.skin.button)
            {
                normal =
                {
                    background = texture,
                    textColor = textColor
                },
                hover =
                {
                    background = texture,
                    textColor = textColor
                },
                active =
                {
                    background = texture,
                    textColor = textColor
                },
                focused =
                {
                    background = texture,
                    textColor = textColor
                },
                fontSize = 12,
                alignment = TextAnchor.MiddleCenter,
                fontStyle = FontStyle.Bold,
                padding = new RectOffset(8, 8, 4, 4)
            };
            return style;
        }

        private void DrawRipperTab()
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.HelpBox(ExporterTerms, MessageType.Warning);
            GUILayout.Space(8f);
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space(4f);
            ripperTabState.DrawPanel(this);
        }

        internal void GoToSettings()
        {
            activeTab = Tab.Settings;
            Repaint();
        }

        internal static void OpenAt(Tab tab)
        {
            Open();
            var window = GetWindow<WPFMAWindow>(false, WindowTitle, true);
            if (window == null)
                return;

            window.activeTab = tab;
            window.Repaint();
        }

        internal static void OpenAtSettings()
        {
            Open();
            var window = GetWindow<WPFMAWindow>(false, WindowTitle, true);
            if (window != null)
                window.GoToSettings();
        }

        private void DrawInfoTab()
        {
            EditorGUILayout.LabelField("Info", EditorStyles.boldLabel);
            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("WPFMA-SDK", EditorStyles.largeLabel);
            EditorGUILayout.LabelField("Who Pays For Models Anyways", EditorStyles.miniLabel);
            EditorGUILayout.LabelField("WPFMA-SDK [BETA 1.17.1]", EditorStyles.miniLabel);
            EditorGUILayout.LabelField("Made by Literal", EditorStyles.miniLabel);
            EditorGUILayout.Space(6f);
            EditorGUILayout.LabelField("Credits", EditorStyles.boldLabel);
            EditorGUILayout.LabelField("Built on the base SDK by google", EditorStyles.miniLabel);

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("Ships with, or needs:", EditorStyles.miniBoldLabel);
            foreach (var credit in BundledCredits)
                EditorGUILayout.LabelField("   " + credit, EditorStyles.miniLabel);

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("Studied while building the ripper:", EditorStyles.miniBoldLabel);
            foreach (var credit in ReferenceCredits)
                EditorGUILayout.LabelField("   " + credit, EditorStyles.miniLabel);

            EditorGUILayout.Space(8f);
            EditorGUILayout.LabelField("Import folder", EditorStyles.boldLabel);
            EditorGUILayout.LabelField(ImportFolderPath, EditorStyles.wordWrappedLabel);
            EditorGUILayout.Space(8f);
            if (DrawActionButton("Open SDK Control Panel", 28f))
                OpenCreatorPanel();
        }

        private void DrawArchiveSection()
        {
            bool unlocked = WPFMAArchive.IsUnlocked;
            if (!DrawCollapsibleStrip("Shader archive", unlocked ? "unlocked" : "locked", "WPFMA.Settings.Archive"))
                return;

            var statusStyle = new GUIStyle(importerRowNameStyle)
            {
                fontSize = 11,
                wordWrap = true,
                normal = { textColor = unlocked ? OkGreen : DimText }
            };

            var statusRect = GUILayoutUtility.GetRect(0f, 22f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(statusRect, RowEven);
            GUI.Label(new Rect(statusRect.x + 8f, statusRect.y, statusRect.width - 16f, statusRect.height),
                WPFMAArchive.Status, statusStyle);

            var serverRect = GUILayoutUtility.GetRect(0f, 26f, GUILayout.ExpandWidth(true));
            float testWidth = ButtonWidth(importerToolbarButtonStyle, "Test");
            var testRect = new Rect(serverRect.xMax - ScrollbarGutter - testWidth - 4f, serverRect.y + 3f, testWidth, 20f);

            GUI.Label(new Rect(serverRect.x + 8f, serverRect.y, 46f, serverRect.height), "server",
                new GUIStyle(importerRowNameStyle) { fontSize = 11, normal = { textColor = FaintText } });

            string editedUrl = EditorGUI.TextField(
                new Rect(serverRect.x + 56f, serverRect.y + 3f, testRect.x - serverRect.x - 62f, 20f),
                WPFMAArchive.BaseUrl);
            if (editedUrl != WPFMAArchive.BaseUrl)
                WPFMAArchive.BaseUrl = editedUrl;

            if (GUI.Button(testRect, "Test", importerToolbarButtonStyle))
            {
                string pingMessage;
                bool reachable;
                try
                {
                    reachable = WPFMAArchive.Ping(out pingMessage);
                }
                catch (Exception e)
                {
                    reachable = false;
                    pingMessage = e.Message;
                }

                EditorUtility.DisplayDialog("WPFMA-SDK",
                    (reachable ? "The archive answered." : "No archive at that address.") +
                    "\n\n" + WPFMAArchive.BaseUrl + "/api/ping.php\n\n" + pingMessage, "OK");
            }

            var rect = GUILayoutUtility.GetRect(0f, 28f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);

            float top = rect.y + 4f;
            const float height = 20f;
            float right = rect.xMax - ScrollbarGutter - 4f;

            if (unlocked)
            {
                float signOutWidth = ButtonWidth(importerToolbarButtonStyle, "Sign out");
                float recheckWidth = ButtonWidth(importerToolbarButtonStyle, "Re-check");

                var signOutRect = new Rect(right - signOutWidth, top, signOutWidth, height);
                if (GUI.Button(signOutRect, "Sign out", importerToolbarButtonStyle))
                    WPFMAArchive.Clear("Signed out on this machine.");

                var recheckRect = new Rect(signOutRect.x - recheckWidth - 5f, top, recheckWidth, height);
                if (GUI.Button(recheckRect, "Re-check", importerToolbarButtonStyle))
                    WPFMAArchive.Check(true);

                var expiry = WPFMAArchive.ExpiresAt;
                GUI.Label(new Rect(rect.x + 8f, rect.y, recheckRect.x - rect.x - 12f, rect.height),
                    expiry > DateTime.MinValue
                        ? "Access expires " + expiry.ToLocalTime().ToString("d MMM yyyy")
                        : "Access does not expire.",
                    new GUIStyle(importerRowNameStyle) { fontSize = 11, normal = { textColor = DimText } });

                return;
            }

            float redeemWidth = ButtonWidth(accentButtonStyle, "Redeem", 20f);
            var redeemRect = new Rect(right - redeemWidth, top, redeemWidth, height);
            if (GUI.Button(redeemRect, "Redeem", accentButtonStyle))
            {
                string message;
                bool ok;
                try
                {
                    ok = WPFMAArchive.Redeem(archiveCode, out message);
                }
                catch (Exception e)
                {
                    ok = false;
                    message = "The redeem call failed: " + e.Message;
                    Debug.LogException(e);
                }

                if (ok)
                    archiveCode = string.Empty;

                EditorUtility.DisplayDialog("WPFMA-SDK", message, "OK");
                GUI.FocusControl(null);
                Repaint();
            }

            float codeWidth = Mathf.Max(80f, redeemRect.x - rect.x - 14f);
            archiveCode = EditorGUI.TextField(new Rect(rect.x + 8f, top, codeWidth, height), archiveCode);
            if (string.IsNullOrEmpty(archiveCode))
                GUI.Label(new Rect(rect.x + 12f, top, codeWidth, height), "access code",
                    new GUIStyle(importerRowNameStyle) { fontSize = 11, normal = { textColor = FaintText } });
        }

        /// <summary>Theme swatches: the whole panel (colors and banners) follows the one picked.</summary>
        private void DrawThemePicker()
        {
            if (!DrawCollapsibleStrip("Theme", WPFMATheme.Current.Name, "WPFMA.Settings.Theme"))
                return;

            EditorGUILayout.LabelField(new GUIContent("Panel color.", "Pick a color for the panel. Banners and buttons change with it; warnings stay amber and errors red."), importerHintStyle);
            EditorGUILayout.Space(4f);

            const float swatchWidth = 74f;
            int perRow = Mathf.Max(1, (int)((position.width - 60f) / (swatchWidth + 6f)));
            var options = WPFMATheme.Options;
            for (int start = 0; start < options.Length; start += perRow)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    for (int i = start; i < Mathf.Min(options.Length, start + perRow); i++)
                    {
                        var option = options[i];
                        bool selected = option == WPFMATheme.Current;
                        var rect = GUILayoutUtility.GetRect(swatchWidth, 30f, GUILayout.Width(swatchWidth));
                        EditorGUI.DrawRect(rect, selected ? Color.white : new Color(0f, 0f, 0f, 0.35f));
                        var inner = new Rect(rect.x + 2f, rect.y + 2f, rect.width - 4f, rect.height - 4f);
                        EditorGUI.DrawRect(inner, option.Swatch);
                        GUI.Label(inner, option.Name, new GUIStyle(EditorStyles.boldLabel)
                        {
                            alignment = TextAnchor.MiddleCenter,
                            fontSize = 11,
                            normal = { textColor = new Color(0.08f, 0.08f, 0.1f) }
                        });
                        EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
                        if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition))
                        {
                            WPFMATheme.Current = option;
                            Event.current.Use();
                            Repaint();
                        }
                        GUILayout.Space(6f);
                    }
                }
                EditorGUILayout.Space(6f);
            }
        }

        private void DrawSettingsTab()
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(importerSectionStyle);

            EditorGUILayout.LabelField("Settings", importerTitleStyle);

            // Pages, like the Tools tab.
            int settingsPage = Mathf.Clamp(EditorPrefs.GetInt(SettingsPageKey, 0), 0, SettingsPageNames.Length - 1);
            int perRow = position.width >= 640f ? SettingsPageNames.Length : (SettingsPageNames.Length + 1) / 2;
            int pickedPage = DrawPageButtons(SettingsPageNames, settingsPage, perRow);
            if (pickedPage != settingsPage)
            {
                EditorPrefs.SetInt(SettingsPageKey, pickedPage);
                settingsPage = pickedPage;
                GUI.FocusControl(null);
            }
            EditorGUILayout.Space(4f);

            if (settingsPage == 0)
                DrawThemePicker();

            if (settingsPage == 2)
                DrawArchiveSection();

            if (settingsPage == 4)
                DrawAvatarToolSettings();

            if (settingsPage == 5)
                DrawWorldToolSettings();

            if (settingsPage == 6)
                DrawTeamSettings();

            if (settingsPage == 0 && DrawCollapsibleStrip("Discord RPC", string.Empty, "WPFMA.Settings.Discord"))
            {

            bool enabled = WPFMADiscordPresence.RpcEnabled;
            bool showPanel = WPFMADiscordPresence.ShowPanelState;
            bool showState = WPFMADiscordPresence.ShowState;

            bool newEnabled = EditorGUILayout.ToggleLeft("Enable Discord RPC", enabled);

            using (new EditorGUI.DisabledScope(!newEnabled))
            {
                showPanel = EditorGUILayout.ToggleLeft(new GUIContent("Show current section", "Importer/Exporter/Info/Settings."), showPanel);
                showState = EditorGUILayout.ToggleLeft(new GUIContent("Show action states", "Importing/Exporting/Preview/Scene."), showState);
            }

            if (newEnabled != enabled || showPanel != WPFMADiscordPresence.ShowPanelState || showState != WPFMADiscordPresence.ShowState)
                WPFMADiscordPresence.Configure(newEnabled, showPanel, showState);

            using (new EditorGUI.DisabledScope(!newEnabled))
            {
                string imageKey = WPFMADiscordPresence.LargeImageKey;
                string editedKey = EditorGUILayout.TextField("Discord art asset", imageKey);
                if (editedKey != imageKey)
                    WPFMADiscordPresence.LargeImageKey = editedKey;

                EditorGUILayout.LabelField(new GUIContent("An asset name from the Discord app.",
                    "Must match an asset uploaded to the Discord application, not a file in this project."),
                    importerPathStyle);
            }

            EditorGUILayout.Space(4f);
            using (new EditorGUILayout.HorizontalScope())
            {
                var statusStyle = new GUIStyle(importerPathStyle)
                {
                    wordWrap = true,
                    normal = { textColor = WPFMADiscordPresence.Connected ? OkGreen : WarnAmber }
                };
                EditorGUILayout.LabelField(WPFMADiscordPresence.ConnectionStatus, statusStyle);

                if (GUILayout.Button("Reconnect", importerToolbarButtonStyle, GUILayout.Width(90f), GUILayout.Height(20f)))
                {
                    WPFMADiscordPresence.Reconnect();
                    Repaint();
                }
            }

            EditorGUILayout.HelpBox(
                "Turn off both visibility toggles to hide status text while keeping RPC enabled, or disable RPC entirely to hide presence completely.",
                MessageType.Info);
            }

            if (settingsPage == 3 && DrawCollapsibleStrip("Tools shown", string.Empty, "WPFMA.Settings.ToolsShown"))
            {
                DrawToolsShownSettings();
            }

            if (settingsPage == 1 && DrawCollapsibleStrip("Package import", string.Empty, "WPFMA.Settings.Queue"))
            {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(
                WPFMA.Editor.WPFMAInstaller.PromptDeclined
                    ? "This project is set to never add the bundled packages."
                    : "Bundled packages are offered when Unity starts.",
                importerHintStyle);
            if (GUILayout.Button("Ask again", GUILayout.Width(90f)))
            {
                EditorApplication.delayCall += WPFMA.Editor.WPFMAInstaller.ResetPrompt;
                GUIUtility.ExitGUI();
            }
            EditorGUILayout.EndHorizontal();

            if (WPFMAPackageImportQueue.Items.Count == 0)
            {
                EditorGUILayout.HelpBox("No queued package imports.", MessageType.None);
            }
            else
            {
                EditorGUILayout.LabelField(
                    WPFMAPackageImportQueue.IsProcessing ? "Currently importing: " + WPFMAPackageImportQueue.GetCurrentPackageName() : "Queued: " + WPFMAPackageImportQueue.Items.Count,
                    importerRowLabelStyle);

                foreach (var queued in WPFMAPackageImportQueue.Items)
                    EditorGUILayout.LabelField(Path.GetFileNameWithoutExtension(queued), importerRowLabelStyle);
            }
            }

            if (settingsPage == 1 && DrawCollapsibleStrip("Package safety", string.Empty, "WPFMA.Settings.Safety"))
            {
                DrawSafetySettings();
            }

            if (settingsPage == 3 && DrawCollapsibleStrip("Hierarchy", string.Empty, "WPFMA.Settings.Hierarchy"))
            {

            if (!WPFMAHierarchyIcons.Available)
            {
                EditorGUILayout.HelpBox(
                    "QHierarchy is not imported yet, so the hierarchy extras are unavailable. It installs itself " +
                    "on the next editor start.",
                    MessageType.None);
            }
            else
            {
                bool highlight = WPFMAAnimationHighlight.Enabled;
                bool editedHighlight = EditorGUILayout.ToggleLeft("Highlight what the open clip animates", highlight);
                if (editedHighlight != highlight)
                    WPFMAAnimationHighlight.Enabled = editedHighlight;

                using (new EditorGUI.DisabledScope(!editedHighlight))
                {
                    var tint = WPFMAAnimationHighlight.HighlightColor;
                    var editedTint = EditorGUILayout.ColorField("Highlight colour", tint);
                    if (editedTint != tint)
                        WPFMAAnimationHighlight.HighlightColor = editedTint;

                    EditorGUILayout.LabelField(new GUIContent("Now: " + WPFMAAnimationHighlight.Status(),
                        "Open a clip in the Animation window and every object it keys is tinted in the hierarchy."),
                        importerHintStyle);

                    if (DrawActionButton("Select what this clip animates", 22f, GUILayout.Width(240f)))
                        WPFMAAnimationHighlight.Reveal();

                    EditorGUILayout.LabelField(new GUIContent("Selects and reveals them.", "Selects them all and opens their parents so they are visible in the hierarchy."), importerHintStyle);
                }

                EditorGUILayout.Space(6f);

                bool on = WPFMAHierarchyIcons.Enabled;
                bool editedOn = EditorGUILayout.ToggleLeft("Hierarchy toggles  (on by default)", on);
                if (editedOn != on)
                    WPFMAHierarchyIcons.Enabled = editedOn;

                EditorGUILayout.LabelField(
                    editedOn
                        ? new GUIContent("Set up on every editor start.", "The eye, mesh icon and component icons are set up on every editor start.")
                        : new GUIContent("Left to QHierarchy.", "Turned off - QHierarchy keeps whatever settings you give it, and the SDK leaves it alone."),
                    importerHintStyle);

                EditorGUILayout.Space(4f);

                using (new EditorGUI.DisabledScope(!editedOn))
                {
                if (DrawActionButton("Re-apply now", 22f, GUILayout.Width(160f)))
                    WPFMAHierarchyIcons.Apply();

                EditorGUILayout.LabelField("Now: " + WPFMAHierarchyIcons.Status(), importerHintStyle);

                EditorGUILayout.Space(4f);

                bool objects = WPFMAHierarchyIcons.ObjectToggle;
                bool editedObjects = EditorGUILayout.ToggleLeft("Object checkbox (hides the whole item)", objects);
                if (editedObjects != objects)
                    WPFMAHierarchyIcons.ObjectToggle = editedObjects;

                bool mesh = WPFMAHierarchyIcons.MeshToggle;
                bool editedMesh = EditorGUILayout.ToggleLeft("Mesh icon (hides just the renderer)", mesh);
                if (editedMesh != mesh)
                    WPFMAHierarchyIcons.MeshToggle = editedMesh;

                EditorGUILayout.LabelField(new GUIContent("Keys into the clip while recording.", "Both key into the clip while the Animation window is recording, the same as an inspector change."), importerHintStyle);

                EditorGUILayout.Space(4f);

                bool icons = WPFMAHierarchyIcons.ComponentIcons;
                bool editedIcons = EditorGUILayout.ToggleLeft("Component icons in the hierarchy", icons);
                if (editedIcons != icons)
                    WPFMAHierarchyIcons.ComponentIcons = editedIcons;

                EditorGUILayout.LabelField(new GUIContent("Click an icon to toggle it.", "Click an icon to turn that component on or off without selecting the object."), importerHintStyle);

                using (new EditorGUI.DisabledScope(!editedIcons))
                {
                    bool play = WPFMAHierarchyIcons.ShowDuringPlayMode;
                    bool editedPlay = EditorGUILayout.ToggleLeft("Keep them in play mode", play);
                    if (editedPlay != play)
                        WPFMAHierarchyIcons.ShowDuringPlayMode = editedPlay;

                    EditorGUILayout.LabelField(
                        "Needed to flip things while an animator is running.",
                        importerHintStyle);

                    bool large = WPFMAHierarchyIcons.LargeIcons;
                    bool editedLarge = EditorGUILayout.ToggleLeft("Bigger icons", large);
                    if (editedLarge != large)
                        WPFMAHierarchyIcons.LargeIcons = editedLarge;
                }
                }
            }
            }

            if (settingsPage == 7 && DrawCollapsibleStrip("Linux", string.Empty, "WPFMA.Settings.Linux"))
            {

            bool onLinux = Application.platform == RuntimePlatform.LinuxEditor;
            if (!onLinux)
            {
                EditorGUILayout.HelpBox("Set these from the Linux editor - they save per install.",
                    MessageType.None);
            }

            using (new EditorGUI.DisabledScope(!onLinux))
            {
                bool software = WPFMAReUpload.ForceSoftwareRendering;
                bool editedSoftware = EditorGUILayout.ToggleLeft(
                    "Run external tools on the software renderer", software);
                if (editedSoftware != software)
                    WPFMAReUpload.ForceSoftwareRendering = editedSoftware;

                EditorGUILayout.LabelField(new GUIContent("For MESA-EGL failures.", "For MESA-EGL failures. Already retried automatically; this skips the first attempt."), importerHintStyle);

                EditorGUILayout.Space(6f);

                bool rebind = WPFMAVrcaPreview.ForceShaderRebind;
                bool editedRebind = EditorGUILayout.ToggleLeft(
                    "Always rebind preview shaders to project shaders", rebind);
                if (editedRebind != rebind)
                    WPFMAVrcaPreview.ForceShaderRebind = editedRebind;

                EditorGUILayout.LabelField(new GUIContent("Fixes magenta bundle shaders.", "Bundle shaders are Direct3D-only, so they draw magenta here. Detected automatically; " + "turn on if one slips through."), importerHintStyle);
            }
            }

            if (settingsPage == 7 && DrawCollapsibleStrip("Wine", string.Empty, "WPFMA.Settings.Wine"))
            {
                bool onLinux = Application.platform == RuntimePlatform.LinuxEditor;


            using (new EditorGUI.DisabledScope(!onLinux))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    string wineOverride = WPFMAReUpload.WineOverride;
                    string editedWine = EditorGUILayout.TextField("Wine build", wineOverride);
                    if (editedWine != wineOverride)
                        WPFMAReUpload.WineOverride = editedWine;

                    if (GUILayout.Button("Browse", importerToolbarButtonStyle, GUILayout.Width(70f), GUILayout.Height(18f)))
                    {
                        string picked = EditorUtility.OpenFilePanel("Select the Wine binary", "/usr/bin", string.Empty);
                        if (!string.IsNullOrEmpty(picked))
                            WPFMAReUpload.WineOverride = picked;
                    }

                    if (GUILayout.Button("Clear", importerToolbarButtonStyle, GUILayout.Width(60f), GUILayout.Height(18f)))
                        WPFMAReUpload.WineOverride = string.Empty;
                }

                EditorGUILayout.LabelField(
                    "Empty uses PATH. Set it for a Lutris or Proton runner.",
                    importerHintStyle);

                EditorGUILayout.Space(6f);

                using (new EditorGUILayout.HorizontalScope())
                {
                    string prefix = WPFMAReUpload.WinePrefix;
                    string editedPrefix = EditorGUILayout.TextField("Wine prefix", prefix);
                    if (editedPrefix != prefix)
                        WPFMAReUpload.WinePrefix = editedPrefix;

                    if (GUILayout.Button("Browse", importerToolbarButtonStyle, GUILayout.Width(70f), GUILayout.Height(18f)))
                    {
                        string picked = EditorUtility.OpenFolderPanel("Select the Wine prefix", string.Empty, string.Empty);
                        if (!string.IsNullOrEmpty(picked))
                            WPFMAReUpload.WinePrefix = picked;
                    }

                    if (GUILayout.Button("Clear", importerToolbarButtonStyle, GUILayout.Width(60f), GUILayout.Height(18f)))
                        WPFMAReUpload.WinePrefix = string.Empty;
                }

                EditorGUILayout.LabelField(new GUIContent("Empty uses ~/.wine.", "Empty uses ~/.wine, shared with every Wine app. A private one keeps the sign-in safe."), importerHintStyle);
            }

            if (onLinux)
            {
                string wine = WPFMAReUpload.Wine;
                EditorGUILayout.Space(4f);

                var wineStyle = new GUIStyle(importerPathStyle)
                {
                    wordWrap = true,
                    normal = { textColor = wine != null ? OkGreen : WarnAmber }
                };

                EditorGUILayout.LabelField(
                    wine != null
                        ? "Using " + wine
                        : string.IsNullOrEmpty(WPFMAReUpload.WineOverride)
                            ? "No Wine on PATH. Only needed for the Windows build."
                            : "That Wine build does not exist.",
                    wineStyle);
            }
            }

            if (settingsPage == 0 && DrawCollapsibleStrip("Build panel theme", string.Empty, "WPFMA.Settings.PanelTheme"))
            {
                bool themed = WPFMAControlPanelTheme.Enabled;
                bool editedThemed = EditorGUILayout.ToggleLeft("Theme the VRChat build panel", themed);
                if (editedThemed != themed)
                    WPFMAControlPanelTheme.Enabled = editedThemed;

                EditorGUILayout.LabelField(new GUIContent("Restyles the build panel safely.", "Applied as an extra stylesheet on top of VRChat's own, so no SDK file is changed and the " + "upload security check still passes. Editing those files directly is what broke uploading before."), importerHintStyle);
            }

            if (settingsPage == 3 && DrawCollapsibleStrip("Animator", string.Empty, "WPFMA.Settings.Animator"))
            {
                bool autoWeight = WPFMALayerWeight.Enabled;
                bool editedAutoWeight = EditorGUILayout.ToggleLeft("New layers start at weight 1", autoWeight);
                if (editedAutoWeight != autoWeight)
                    WPFMALayerWeight.Enabled = editedAutoWeight;

                EditorGUILayout.LabelField(new GUIContent("New layers start at weight 1.", "Unity creates every new layer at weight 0. Only layers added from now on are touched; " + "existing zeroes are left alone, since plenty of rigs drive those from an Animator Layer Control."), importerHintStyle);

                EditorGUILayout.Space(4f);

                bool instant = WPFMATransitionDefaults.Enabled;
                bool editedInstant = EditorGUILayout.ToggleLeft("New transitions are instant", instant);
                if (editedInstant != instant)
                    WPFMATransitionDefaults.Enabled = editedInstant;

                EditorGUILayout.LabelField(new GUIContent("New transitions become instant.", "Clears Has Exit Time and sets duration and offset to 0, which is what a toggle wants. " + "Only transitions made from now on; existing ones keep their tuning."), importerHintStyle);

                EditorGUILayout.Space(4f);

                if (DrawActionButton("Fix the selected controller now", 22f, GUILayout.Width(240f)))
                {
                    var controller = Selection.activeObject as UnityEditor.Animations.AnimatorController;
                    if (controller == null)
                    {
                        Debug.LogWarning("[WPFMA-SDK] Select an Animator Controller first.");
                    }
                    else
                    {
                        int fixedCount = WPFMALayerWeight.FixAll(controller);
                        int instantCount = WPFMATransitionDefaults.FixAll(controller);
                        Debug.Log("[WPFMA-SDK] '" + controller.name + "': " + fixedCount +
                                  " layer(s) set to weight 1, " + instantCount + " transition(s) made instant.");
                    }
                }

                EditorGUILayout.LabelField(new GUIContent("Both, on the selected controller.", "Applies both of the above to every layer and transition on the selected controller."), importerHintStyle);
            }

            if (settingsPage == 2 && DrawCollapsibleStrip("Exporter", string.Empty, "WPFMA.Settings.Ripper"))
            {
                bool show = !ExporterHidden;
                bool editedShow = EditorGUILayout.ToggleLeft(new GUIContent("Show the Exporter tab",
                    "Off by default. Untick to hide the Exporter tab and its Welcome card again."), show);
                if (editedShow && !show && !AgreeToExporter())
                    editedShow = false;
                if (editedShow != show)
                    ExporterHidden = !editedShow;
                EditorGUILayout.LabelField(ExporterTerms, importerHintStyle);
                if (editedShow)
                    ripperTabState.DrawSettingsSection(this);
            }

            if (settingsPage == 0 && DrawCollapsibleStrip("Reloading", string.Empty, "WPFMA.Settings.Reloading"))
            {
                Toggle("Pick up file changes while Unity is in the background",
                    "Scripts and files changed in another program are refreshed and compiled without clicking into Unity.",
                    WPFMABackgroundRefresh.Enabled, v => WPFMABackgroundRefresh.Enabled = v);
                EditorGUILayout.LabelField(new GUIContent("Refreshes while Unity is in the background.", "Unity normally only notices changed files when you click back into it. Follows Unity's own " + "Auto Refresh preference, and waits while in Play mode."), importerHintStyle);
            }

            if (settingsPage == 0 && DrawCollapsibleStrip("Welcome splash", string.Empty, "WPFMA.Settings.Welcome"))
            {

            bool showWelcome = WPFMAWelcomeSettings.ShowOnFreshInstall;
            bool newShowWelcome = EditorGUILayout.ToggleLeft("Show one-time welcome on fresh install", showWelcome);
            if (newShowWelcome != showWelcome)
                WPFMAWelcomeSettings.SetShowOnFreshInstall(newShowWelcome);

            if (DrawActionButton("Open welcome now", 24f, GUILayout.Width(180f)))
                WPFMAWelcomeWindow.OpenFromMenu();
            }

            if (settingsPage == 3)
                DrawToolOptionSettings();

            EditorGUILayout.EndVertical();
            GUILayout.Space(8f);
            EditorGUILayout.EndHorizontal();
        }

        private static readonly string[] SettingsPageNames = { "General", "Importer", "Exporter", "Tools", "Avatars", "Worlds", "Team", "System" };
        private const string SettingsPageKey = "WPFMA.Settings.Page";
        private const string HideTeamKey = "WPFMA.Settings.HideTeam";

        /// <summary>Settings > Team can hide the Team tab, for people who never build together.</summary>
        internal static bool TeamHidden
        {
            get { return EditorPrefs.GetBool(HideTeamKey, false); }
            set { EditorPrefs.SetBool(HideTeamKey, value); }
        }

        /// <summary>Team's own options (also in Team's setup window), so they can be changed any time.</summary>
        private void DrawTeamSettings()
        {
            if (!DrawCollapsibleStrip("Team", string.Empty, "WPFMA.Settings.Team"))
                return;

            bool showTab = !TeamHidden;
            bool editedShowTab = EditorGUILayout.ToggleLeft(new GUIContent("Show the Team tab",
                "Untick if you never build together. Turn it back on here any time."), showTab);
            if (editedShowTab != showTab)
                TeamHidden = !editedShowTab;
            if (!editedShowTab)
                return;

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("When you join", EditorStyles.boldLabel);
            Toggle("Get the host's project automatically", "No extra prompt when you join or reconnect.",
                WPFMA.Team.TeamFiles.AutoGetProject, v => WPFMA.Team.TeamFiles.AutoGetProject = v);
            Toggle("Install free packages the host uses", "VRCFury, Modular Avatar, lilToon and similar. Paid ones are listed for you to get.",
                WPFMA.Team.TeamProject.AutoInstall, v => WPFMA.Team.TeamProject.AutoInstall = v);
            Toggle("Follow the host to every scene", "Off: you start in the host's scene, then work wherever you like. Opening a scene a teammate is in joins them.",
                WPFMA.Team.TeamScene.FollowPreference, v => WPFMA.Team.TeamScene.FollowPreference = v);

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("While you build", EditorStyles.boldLabel);
            Toggle("Make what a teammate has selected read-only for me", "So you never both edit the same object.",
                WPFMA.Team.TeamLocks.Enabled, v => WPFMA.Team.TeamLocks.Enabled = v);
            Toggle("Save changed assets automatically", "Animators, menus and clips reach your teammates without pressing Save.",
                WPFMA.Team.TeamFiles.AutoSave, v => WPFMA.Team.TeamFiles.AutoSave = v);
            Toggle("Show a stand-in for shaders I don't have", "Instead of pink. Only how it looks for you; files are never changed.",
                WPFMA.Team.TeamStandIns.Enabled, v => WPFMA.Team.TeamStandIns.Enabled = v);
            Toggle("Show teammates' cameras and selections", null,
                WPFMA.Team.TeamView.ShowCamera && WPFMA.Team.TeamView.ShowSelection,
                v => { WPFMA.Team.TeamView.ShowCamera = v; WPFMA.Team.TeamView.ShowSelection = v; });
            Toggle("Show notes in the Scene view", "Chat, reconnects and uploads. Edits never pop up; they're in the Change log.",
                WPFMA.Team.TeamToasts.Enabled, v => WPFMA.Team.TeamToasts.Enabled = v);
            Toggle("Fix an out-of-sync scene automatically", "Off: the Team tab shows which objects differ and a Fix button instead.",
                WPFMA.Team.TeamScene.AutoFix, v => WPFMA.Team.TeamScene.AutoFix = v);

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("How teammates see you", EditorStyles.boldLabel);
            var shapes = WPFMA.Team.TeamLook.Shapes;
            int shape = EditorGUILayout.Popup(new GUIContent("Shape", "What your camera looks like in their Scene view."),
                Mathf.Max(0, Array.IndexOf(shapes, WPFMA.Team.TeamLook.Shape)), shapes);
            WPFMA.Team.TeamLook.Shape = shapes[shape];
            using (new EditorGUILayout.HorizontalScope())
            {
                var picked = WPFMA.Team.TeamLook.ShapeColor;
                bool own = EditorGUILayout.ToggleLeft(new GUIContent("My own color",
                    "Colors your shape, arrow and hat. Off: they use your teammate color. Your name and a ring under you always stay in your teammate color, so people can tell who is who."),
                    picked.HasValue, GUILayout.Width(150f));
                if (own)
                {
                    var color = EditorGUILayout.ColorField(GUIContent.none, picked ?? WPFMA.Team.TeamSession.LocalColor, true, false, false);
                    WPFMA.Team.TeamLook.ShapeColor = color;
                }
                else if (picked.HasValue)
                {
                    WPFMA.Team.TeamLook.ShapeColor = null;
                }
            }
            var hats = WPFMA.Team.TeamLook.Hats;
            int hat = EditorGUILayout.Popup(new GUIContent("Hat", "Sits on top of your shape. It uses your color (or your teammate color)."),
                Mathf.Max(0, Array.IndexOf(hats, WPFMA.Team.TeamLook.Hat)), hats);
            WPFMA.Team.TeamLook.Hat = hats[hat];
            var faces = WPFMA.Team.TeamLook.Faces;
            int face = EditorGUILayout.Popup(new GUIContent("Face", "On the front of your shape. Points where you look."),
                Mathf.Max(0, Array.IndexOf(faces, WPFMA.Team.TeamLook.Face)), faces);
            WPFMA.Team.TeamLook.Face = faces[face];
            EditorGUILayout.Space(4f);
            var previewRect = GUILayoutUtility.GetRect(200f, 200f, GUILayout.ExpandWidth(true));
            if (WPFMA.Team.TeamLook.DrawPreview(previewRect))
                Repaint();
            EditorGUILayout.LabelField(new GUIContent("Your look in teammates' Scene view.", "How you'll look in a teammate's Scene view. Your name and ring use your teammate color, which each " + "teammate's editor picks, so it may not be this one for them."), importerHintStyle);

            EditorGUILayout.Space(4f);
            using (new EditorGUI.DisabledScope(WPFMA.Team.TeamSession.State != WPFMA.Team.TeamState.Idle))
            {
                int port = Mathf.Clamp(EditorGUILayout.IntField(new GUIContent("Port", "Only change this if something else on your PC uses it. Can't change during a session."),
                    WPFMA.Team.TeamSession.Port), 1024, 65535);
                if (port != WPFMA.Team.TeamSession.Port)
                    WPFMA.Team.TeamSession.Port = port;
            }
            EditorGUILayout.LabelField(new GUIContent("Script trust is asked each session.", "Whether to trust teammates' scripts is chosen each time you host or join."), importerHintStyle);
            if (GUILayout.Button("Team doctor: check my connection", EditorStyles.miniButton, GUILayout.Width(210f)))
                WPFMA.Team.TeamDoctor.Open();
        }

        /// <summary>Settings > Tools: options shared by avatar and world tools.</summary>
        private void DrawToolOptionSettings()
        {
            if (DrawCollapsibleStrip("Change log", string.Empty, "WPFMA.Settings.ChangeLog"))
            {
                Toggle("Save a copy before every change", "So Revert in the Change log can put things back, even after Unity was closed.",
                    WPFMAChangeLog.Enabled, v => WPFMAChangeLog.Enabled = v);
                using (new EditorGUI.DisabledScope(!WPFMAChangeLog.Enabled))
                {
                    int keep = EditorGUILayout.IntSlider("Keep the last", WPFMAChangeLog.Keep, 5, 200);
                    if (keep != WPFMAChangeLog.Keep)
                        WPFMAChangeLog.Keep = keep;
                }
                EditorGUILayout.LabelField("Older copies are deleted as new ones are made.", importerHintStyle);
            }

            if (DrawCollapsibleStrip("Triangle counter", string.Empty, "WPFMA.Settings.TriangleCounter"))
            {
                Toggle("Include children", null, WPFMATriangleCounterSection.Children, v => WPFMATriangleCounterSection.Children = v);
                Toggle("Include hidden objects", null, WPFMATriangleCounterSection.Inactive, v => WPFMATriangleCounterSection.Inactive = v);
            }

            if (DrawCollapsibleStrip("Texture optimizer", string.Empty, "WPFMA.Settings.Textures"))
            {
                EditorGUILayout.LabelField(new GUIContent("Texture optimizer defaults.", "What the Texture optimizer starts with, for avatars and worlds."), importerHintStyle);
                WPFMAToolDefaults.TextureMaxSize = SizePopup("Max size", WPFMAToolDefaults.TextureMaxSize, TextureSizes);
                Toggle("Compress uncompressed textures", null, WPFMAToolDefaults.TextureCompress, v => WPFMAToolDefaults.TextureCompress = v);
                Toggle("Crunch compression", "Much smaller download, slightly softer.", WPFMAToolDefaults.TextureCrunch, v => WPFMAToolDefaults.TextureCrunch = v);
                if (WPFMAToolDefaults.TextureCrunch)
                    WPFMAToolDefaults.TextureCrunchQuality = EditorGUILayout.IntSlider("  Crunch quality", WPFMAToolDefaults.TextureCrunchQuality, 0, 100);
                Toggle("Streaming mipmaps", "Less memory in game.", WPFMAToolDefaults.TextureStreamingMips, v => WPFMAToolDefaults.TextureStreamingMips = v);
                Toggle("Quest settings (ASTC 6x6)", null, WPFMAToolDefaults.TextureQuest, v => WPFMAToolDefaults.TextureQuest = v);
                if (WPFMAToolDefaults.TextureQuest)
                    WPFMAToolDefaults.TextureQuestMaxSize = SizePopup("  Quest max size", WPFMAToolDefaults.TextureQuestMaxSize, TextureSizes);
                Toggle("Keep colour ramps and lookup textures sharp", "Compressing them makes visible bands.", WPFMAToolDefaults.TextureKeepRamps, v => WPFMAToolDefaults.TextureKeepRamps = v);
                Toggle("Turn on mipmaps where they're off", "No shimmering far away, a third more memory.", WPFMAToolDefaults.TextureMipmaps, v => WPFMAToolDefaults.TextureMipmaps = v);
                ResetButton("Textures.");
            }
        }

        /// <summary>Settings > Avatars: what the avatar tools start with.</summary>
        private void DrawAvatarToolSettings()
        {
            if (WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds)
                EditorGUILayout.HelpBox("This is a world project, so these tools aren't in the Tools tab here.", MessageType.None);

            EditorGUILayout.LabelField(new GUIContent("What each tool starts with.", "What each tool starts with. Changing an option inside a tool saves it here too."), importerHintStyle);
            EditorGUILayout.Space(2f);

            if (DrawCollapsibleStrip("Avatar setup", string.Empty, "WPFMA.Settings.Defaults.Setup"))
            {
                Toggle("Put the view position between the eyes", null, WPFMAToolDefaults.SetupViewFromEyes, v => WPFMAToolDefaults.SetupViewFromEyes = v);
                Toggle("Set up lip sync from viseme blendshapes", null, WPFMAToolDefaults.SetupLipSync, v => WPFMAToolDefaults.SetupLipSync = v);
                Toggle("Set up eye look and blink", null, WPFMAToolDefaults.SetupEyeLook, v => WPFMAToolDefaults.SetupEyeLook = v);
            }

            if (DrawCollapsibleStrip("Toggle creator", string.Empty, "WPFMA.Settings.Defaults.Toggle"))
            {
                Toggle("Starts on", null, WPFMAToolDefaults.ToggleStartsOn, v => WPFMAToolDefaults.ToggleStartsOn = v);
                Toggle("Saved", "Stays the same when you change avatar or rejoin.", WPFMAToolDefaults.ToggleSaved, v => WPFMAToolDefaults.ToggleSaved = v);
                Toggle("Sync over the network", "Untick for local-only toggles.", WPFMAToolDefaults.ToggleSynced, v => WPFMAToolDefaults.ToggleSynced = v);
                Toggle("Add to menu", null, WPFMAToolDefaults.ToggleAddToMenu, v => WPFMAToolDefaults.ToggleAddToMenu = v);
                Toggle("Put toggles in one shared layer", "Lighter for the avatar than a layer per toggle.", WPFMAToolDefaults.ToggleCombined, v => WPFMAToolDefaults.ToggleCombined = v);
#if WPFMA_VRC_AVATARS
                WPFMAToolDefaults.ToggleWriteDefaults = (int)(WPFMAToggleCreator.WriteDefaults)EditorGUILayout.EnumPopup(
                    "Write defaults", (WPFMAToggleCreator.WriteDefaults)WPFMAToolDefaults.ToggleWriteDefaults);
#endif
            }

            if (DrawCollapsibleStrip("Other avatar tools", string.Empty, "WPFMA.Settings.Defaults.AvatarOther"))
            {
                EditorGUILayout.LabelField("Component copier", EditorStyles.boldLabel);
                Toggle("Overwrite components the new avatar already has", null, WPFMAToolDefaults.CopierOverwrite, v => WPFMAToolDefaults.CopierOverwrite = v);
                Toggle("Create empty objects that only exist on the old avatar", null, WPFMAToolDefaults.CopierCreateMissing, v => WPFMAToolDefaults.CopierCreateMissing = v);

                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Bulk shader swap", EditorStyles.boldLabel);
                Toggle("Make copies of the materials", "Keeps the originals untouched.", WPFMAToolDefaults.ShaderSwapCopies, v => WPFMAToolDefaults.ShaderSwapCopies = v);

                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("PhysBones", EditorStyles.boldLabel);
                Toggle("Update PhysBones that are already there", null, WPFMAToolDefaults.PhysBonesUpdateExisting, v => WPFMAToolDefaults.PhysBonesUpdateExisting = v);

                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Bounds & lighting fix", EditorStyles.boldLabel);
                WPFMAToolDefaults.BoundsAnchor = EditorGUILayout.Popup("Lighting follows", Mathf.Clamp(WPFMAToolDefaults.BoundsAnchor, 0, WPFMABoundsFix.AnchorNames.Length - 1), WPFMABoundsFix.AnchorNames);
                Toggle("Also fix the bounds", null, WPFMAToolDefaults.BoundsFixBounds, v => WPFMAToolDefaults.BoundsFixBounds = v);

                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Blendshape baker", EditorStyles.boldLabel);
                Toggle("Remove unused shapes at 0", null, WPFMAToolDefaults.BlendshapeRemoveZero, v => WPFMAToolDefaults.BlendshapeRemoveZero = v);

                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Lists", EditorStyles.boldLabel);
                Toggle("Performance rank: only show what lowers the rank", null, WPFMAToolDefaults.PerformanceOnlyProblems, v => WPFMAToolDefaults.PerformanceOnlyProblems = v);
                Toggle("Parameter budget: only show problems", null, WPFMAToolDefaults.ParametersOnlyProblems, v => WPFMAToolDefaults.ParametersOnlyProblems = v);
            }

            ResetButton("Avatar.");
        }

        /// <summary>Settings > Worlds: what the world tools start with.</summary>
        private void DrawWorldToolSettings()
        {
            if (WPFMA.Editor.WPFMAInstaller.PanelKind != WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds)
                EditorGUILayout.HelpBox("This is an avatar project, so these tools aren't in the Tools tab here. They're saved for your world projects.", MessageType.None);

            EditorGUILayout.LabelField(new GUIContent("What each tool starts with.", "What each tool starts with. Changing an option inside a tool saves it here too."), importerHintStyle);
            EditorGUILayout.Space(2f);

            if (DrawCollapsibleStrip("Setup and lighting", string.Empty, "WPFMA.Settings.Defaults.WorldLight"))
            {
                Toggle("World setup: include post-processing", "Light bloom and neutral tonemapping on the reference camera.",
                    WPFMAToolDefaults.WorldPostProcessing, v => WPFMAToolDefaults.WorldPostProcessing = v);
                WPFMAToolDefaults.WorldProbeSpacing = EditorGUILayout.Slider("Light probe spacing (m)", WPFMAToolDefaults.WorldProbeSpacing, 0.5f, 10f);
                Toggle("Light volumes: one per selected object", "For example one per room.",
                    WPFMAToolDefaults.WorldVolumePerObject, v => WPFMAToolDefaults.WorldVolumePerObject = v);
            }

            if (DrawCollapsibleStrip("Optimizing", string.Empty, "WPFMA.Settings.Defaults.WorldOptimize"))
            {
                WPFMAToolDefaults.WorldAtlasSize = SizePopup("Atlas size", WPFMAToolDefaults.WorldAtlasSize, AtlasSizes);
                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Occlusion culling", EditorStyles.boldLabel);
                WPFMAToolDefaults.WorldSmallestOccluder = EditorGUILayout.Slider("Smallest occluder (m)", WPFMAToolDefaults.WorldSmallestOccluder, 0.5f, 10f);
                WPFMAToolDefaults.WorldSmallestHole = EditorGUILayout.Slider("Smallest hole (m)", WPFMAToolDefaults.WorldSmallestHole, 0.05f, 2f);
                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Draw-distance culling", EditorStyles.boldLabel);
                WPFMAToolDefaults.WorldCullBelowSize = EditorGUILayout.Slider("Props smaller than (m)", WPFMAToolDefaults.WorldCullBelowSize, 0.1f, 5f);
                WPFMAToolDefaults.WorldCullPercent = EditorGUILayout.Slider("Hide below (% of screen)", WPFMAToolDefaults.WorldCullPercent, 0.2f, 10f);
            }

            if (DrawCollapsibleStrip("Interactions", string.Empty, "WPFMA.Settings.Defaults.WorldInteract"))
            {
                EditorGUILayout.LabelField("Toggle & button maker", EditorStyles.boldLabel);
                Toggle("Everyone sees it change (synced)", null, WPFMAToolDefaults.WorldToggleSynced, v => WPFMAToolDefaults.WorldToggleSynced = v);
                Toggle("Start switched off", null, WPFMAToolDefaults.WorldToggleStartsOff, v => WPFMAToolDefaults.WorldToggleStartsOff = v);

                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Pickup maker", EditorStyles.boldLabel);
                Toggle("Everyone sees it move (Object Sync)", null, WPFMAToolDefaults.WorldPickupSynced, v => WPFMAToolDefaults.WorldPickupSynced = v);
                Toggle("Falls when dropped (gravity)", null, WPFMAToolDefaults.WorldPickupGravity, v => WPFMAToolDefaults.WorldPickupGravity = v);
                Toggle("Floats where it is let go (kinematic)", null, WPFMAToolDefaults.WorldPickupStaysPut, v => WPFMAToolDefaults.WorldPickupStaysPut = v);

                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Teleport maker", EditorStyles.boldLabel);
                Toggle("Step onto it (otherwise players click it)", null, WPFMAToolDefaults.WorldTeleportWalkIn, v => WPFMAToolDefaults.WorldTeleportWalkIn = v);
                Toggle("Two-way: add a pad that comes back", null, WPFMAToolDefaults.WorldTeleportTwoWay, v => WPFMAToolDefaults.WorldTeleportTwoWay = v);

                EditorGUILayout.Space(2f);
                EditorGUILayout.LabelField("Seats, sound and video", EditorStyles.boldLabel);
                WPFMAToolDefaults.WorldSeatHeight = EditorGUILayout.Slider("Seat height (m)", WPFMAToolDefaults.WorldSeatHeight, 0.1f, 1.2f);
                WPFMAToolDefaults.WorldAudioFade = EditorGUILayout.Slider("Audio zone fade time (s)", WPFMAToolDefaults.WorldAudioFade, 0.1f, 6f);
                WPFMAToolDefaults.WorldVideoStreams = EditorGUILayout.Popup("Video player", WPFMAToolDefaults.WorldVideoStreams ? 1 : 0,
                    new[] { "Videos (Unity player)", "Videos + livestreams (AVPro)" }) == 1;
                WPFMAToolDefaults.WorldVideoWidth = EditorGUILayout.Slider("Screen width (m)", WPFMAToolDefaults.WorldVideoWidth, 1f, 30f);
                WPFMAToolDefaults.WorldVideoRange = EditorGUILayout.Slider("Sound reaches (m)", WPFMAToolDefaults.WorldVideoRange, 5f, 200f);
            }

            ResetButton("World.");
        }

        private static readonly int[] TextureSizes = { 256, 512, 1024, 2048, 4096 };
        private static readonly int[] AtlasSizes = { 1024, 2048, 4096 };

        private static int SizePopup(string label, int value, int[] sizes)
        {
            int index = Mathf.Max(0, Array.IndexOf(sizes, value));
            return sizes[EditorGUILayout.Popup(label, index, sizes.Select(x => x.ToString()).ToArray())];
        }

        private void ResetButton(string group)
        {
            EditorGUILayout.Space(4f);
            if (GUILayout.Button("Reset these to how they shipped", importerToolbarButtonStyle, GUILayout.Width(220f), GUILayout.Height(20f)))
            {
                WPFMAToolDefaults.Reset(group);
                GUI.FocusControl(null);
                Repaint();
            }
        }

        /// <summary>Page buttons that are all the same width, wrapping after <paramref name="perRow"/>. Returns the page picked.</summary>
        private int DrawPageButtons(string[] names, int current, int perRow)
        {
            const float gap = 4f;
            int picked = current;

            // A label that wouldn't fit (like "Check & fix" with six pages in a narrow window) moves the buttons onto two rows.
            float available = Mathf.Max(100f, EditorGUIUtility.currentViewWidth - 40f);
            while (perRow > 1)
            {
                float each = (available - gap * (perRow - 1)) / perRow;
                if (!names.Any(n => tabButtonStyle.CalcSize(new GUIContent(n)).x + 8f > each))
                    break;
                perRow = (names.Length + 1) / 2 < perRow ? (names.Length + 1) / 2 : perRow - 1;
            }

            for (int start = 0; start < names.Length; start += perRow)
            {
                if (start > 0)
                    GUILayout.Space(gap);
                Rect row = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
                float width = (row.width - gap * (perRow - 1)) / perRow;
                for (int i = start; i < Mathf.Min(start + perRow, names.Length); i++)
                {
                    float x = Mathf.Round(row.x + (i - start) * (width + gap));
                    float right = Mathf.Round(row.x + (i - start) * (width + gap) + width);
                    if (GUI.Button(new Rect(x, row.y, right - x, row.height), names[i], i == current ? activeTabButtonStyle : tabButtonStyle))
                        picked = i;
                }
            }
            return picked;
        }

        private static void Toggle(string label, string tip, bool value, Action<bool> set)
        {
            bool edited = EditorGUILayout.ToggleLeft(new GUIContent(label, tip), value);
            if (edited != value)
                set(edited);
        }

        private static readonly string[] ToolPageNames = { "Setup", "Check & fix", "Optimize", "Files" };
        private static readonly string[] WorldPageNames = { "Setup", "Build", "Check & fix", "Lighting", "Optimize", "Files" };
        private const string ToolPagePrefKey = "WPFMA.Tools.Page";
        private const string HiddenToolPrefix = "WPFMA.Tools.Hidden.";

        internal sealed class ToolEntry
        {
            public string Id;
            public string Title;
            public string Keywords;
            public int Page;
            public Action Draw;
        }

        [NonSerialized] private string toolSearch = string.Empty;

        internal static bool IsToolHidden(string id)
        {
            return EditorPrefs.GetBool(HiddenToolPrefix + id, false);
        }

        internal static void SetToolHidden(string id, bool hidden)
        {
            if (hidden)
                EditorPrefs.SetBool(HiddenToolPrefix + id, true);
            else
                EditorPrefs.DeleteKey(HiddenToolPrefix + id);
        }

        private ToolEntry Tool(string id, string title, string keywords, int page, Action draw)
        {
            return new ToolEntry { Id = id, Title = title, Keywords = keywords, Page = page, Draw = draw };
        }

        internal List<ToolEntry> ToolList(bool world)
        {
            var s = importerSectionStyle;
            if (!world)
            {
                return new List<ToolEntry>
                {
                    Tool("avatar-setup", "Avatar setup", "descriptor fx controller menu parameters lip sync visemes eyes blink view fbx humanoid new model", 0, () => WPFMAAvatarSetupSection.Draw(s)),
                    Tool("component-copier", "Component copier", "copy transfer physbones contacts constraints vrcfury modular avatar reimport", 0, () => WPFMAComponentCopierSection.Draw(s)),
                    Tool("toggle-creator", "Toggle creator", "toggle menu animation on off clothes", 0, () => WPFMAToggleCreatorSection.Draw(s, importerTitleStyle, importerPathStyle)),
                    Tool("physbones", "PhysBones", "physbone hair tail skirt ears presets dynamics jiggle", 0, () => WPFMAPhysBoneSection.Draw(s)),
                    Tool("pose", "Pose & blendshapes", "pose reset t-pose tpose bind pose blendshapes zero revert model pumkin", 0, () => WPFMAPoseToolsSection.Draw(s)),
                    Tool("sprite-mouth", "Sprite mouth", "sprite sheet mouth 2d png talk visemes voice lip sync pngtuber frames", 0, () => WPFMASpriteMouthSection.Draw(s)),
                    Tool("avatar-size", "Avatar size", "scale size height bigger smaller resize view position eyes pumkin", 0, () => WPFMAScaleSection.Draw(s)),
                    Tool("modular-avatar", "Modular Avatar", "setup outfit clothing merge armature ma", 0, DrawModularAvatar),
                    Tool("pre-upload", "Pre-upload check", "check errors warnings upload ready missing scripts pink", 1, () => WPFMAPreUploadSection.Draw(s)),
                    Tool("write-defaults", "Write defaults", "write defaults wd on off mixed toggles stuck frozen face animator fx direct blend tree", 1, () => WPFMAWriteDefaultsSection.Draw(s)),
                    Tool("removal", "Removal", "remove delete strip components physbones colliders contacts constraints particles lights audio cloth missing scripts empty dynamic bones pumkin", 1, () => WPFMARemovalSection.Draw(s)),
                    Tool("remove-by-name", "Remove by name", "remove delete objects name editoronly armature cleanup pumkin", 1, () => WPFMARemoveByNameSection.Draw(s)),
                    Tool("package-checker", "Package checker", "package checker safety token logger malware virus dll scan quarantine discord rat", 1, () => WPFMASafetySection.Draw(s)),
                    Tool("missing-references", "Missing references", "missing references broken none null scripts prefab deleted find", 1, () => WPFMAMissingReferencesSection.Draw(s)),
                    Tool("performance", "Performance rank", "rank quest pc very poor excellent stats polygons triangles", 1, () => WPFMAPerformanceSection.Draw(s)),
                    Tool("triangle-counter", "Triangle counter", "triangles polygons polys poly count vertices selected object mesh heavy", 1, () => WPFMATriangleCounterSection.Draw(s)),
                    Tool("parameter-budget", "Parameter budget", "parameters bits synced 256 unused expression", 1, () => WPFMAParameterBudgetSection.Draw(s)),
                    Tool("face-tracking", "Face tracking checker", "face tracking arkit unified expressions sranipal vrcft blendshapes", 1, () => WPFMAFaceTrackingSection.Draw(s)),
                    Tool("path-fixer", "Animation path fixer", "animation broken paths renamed moved missing clips", 1, () => WPFMAAnimationPathFixerSection.Draw(s)),
                    Tool("blendshape-baker", "Blendshape baker", "blendshape shape keys bake body sliders remove", 2, () => WPFMABlendshapeBakerSection.Draw(s)),
                    Tool("physbone-optimizer", "PhysBone optimizer", "physbone optimize collision checks colliders is animated performance bones", 2, () => WPFMAPhysBoneOptimizerSection.Draw(s)),
                    Tool("bounds-fix", "Bounds & lighting fix", "bounds anchor override lighting probe culling disappear vanish meshes", 2, () => WPFMABoundsFixSection.Draw(s)),
                    Tool("heatmap", "Performance heatmap", "heatmap heat map heavy triangles materials texture memory overdraw transparent scene view colors", 2, () => WPFMAHeatmapSection.Draw(s)),
                    Tool("avatar-compressor", "Avatar Compressor", "compress textures size download lac", 2, DrawAvatarCompressor),
                    Tool("texture-optimizer", "Texture optimizer", "textures compression crunch max size quest astc mipmaps", 2, () => WPFMATextureOptimizerSection.Draw(s)),
                    Tool("shader-swap", "Bulk shader swap", "shader swap materials poiyomi liltoon mobile quest", 2, () => WPFMAShaderSwapSection.Draw(s)),
                    Tool("quest-switch", "Easy Quest Switch", "quest android pc switch platform eqs", 2, DrawQuestSwitch),
                    Tool("fbx", "FBX exporter", "fbx export model blender", 3, DrawFbxExporterSection),
                    Tool("package-creator", "Package creator", "unitypackage export package", 3, DrawPackageCreator),
                    Tool("thumbnail", "Thumbnail studio", "thumbnail picture image upload photo text effects", 3, () => WPFMAThumbnailSection.Draw(s)),
                    Tool("reupload", "Re-upload", "reupload upload avatar", 3, () => WPFMAReUploadSection.Draw(s, importerTitleStyle, importerPathStyle)),
                    Tool("renamer", "Bulk renamer", "rename bulk batch names numbering prefix suffix find replace", 3, () => WPFMARenamerSection.Draw(s)),
                    Tool("change-log", "Change log", "undo revert history snapshot restore changes", 3, () => WPFMAChangeLogSection.Draw(s))
                };
            }

            return new List<ToolEntry>
            {
                Tool("world-setup", "World setup", "scene descriptor vrcworld spawn respawn reference camera post processing", 0, () => WPFMAWorldSetupSection.Draw(s)),
                Tool("quick-prefabs", "Quick prefabs", "mirror chair pedestal video player portal pens prefab", 0, () => WPFMAWorldPrefabsSection.Draw(s)),
                Tool("toggle-maker", "Toggle & button maker", "toggle button mirror lights udon switch", 0, () => WPFMAToggleMakerSection.Draw(s)),
                Tool("pickup-maker", "Pickup maker", "pickup grab object sync rigidbody", 0, () => WPFMAPickupMakerSection.Draw(s)),
                Tool("audio-zone", "Audio zone maker", "audio music ambience zone fade area", 0, () => WPFMAAudioZoneSection.Draw(s)),
                Tool("teleport", "Teleport maker", "teleport pad move player portal", 0, () => WPFMATeleportSection.Draw(s)),
                Tool("seat", "Seat maker", "seat chair sit station bench sofa", 0, () => WPFMASeatSection.Draw(s)),
                Tool("video-screen", "Video screen helper", "video player screen stream avpro", 0, () => WPFMAVideoScreenSection.Draw(s)),
                Tool("placement", "Placement tools", "drop floor scatter grid copies random props trees", 1, () => WPFMAPlacementSection.Draw(s)),
                Tool("colliders", "Collider helper", "collider floor walls walkthrough fall through", 1, () => WPFMAColliderSection.Draw(s)),
                Tool("player-guide", "Player-size guide", "player size height door ceiling scale", 1, () => WPFMAPlayerGuideSection.Draw(s)),
                Tool("world-check", "World pre-upload check", "check errors warnings upload ready", 2, () => WPFMAWorldCheckSection.Draw(s)),
                Tool("package-checker", "Package checker", "package checker safety token logger malware virus dll scan quarantine discord rat", 2, () => WPFMASafetySection.Draw(s)),
                Tool("missing-references", "Missing references", "missing references broken none null scripts prefab deleted find", 2, () => WPFMAMissingReferencesSection.Draw(s)),
                Tool("world-stats", "World stats", "stats triangles materials size count", 2, () => WPFMAWorldStatsSection.Draw(s)),
                Tool("triangle-counter", "Triangle counter", "triangles polygons polys poly count vertices selected object mesh heavy", 2, () => WPFMATriangleCounterSection.Draw(s)),
                Tool("build-size", "Build size explorer", "build size download heavy assets vrcw mb", 2, () => WPFMABuildSizeSection.Draw(s)),
                Tool("lighting", "Lighting helper", "bake lighting static lights probes lightmaps bakery realtime point lights editoronly", 3, () => WPFMALightingSection.Draw(s)),
                Tool("light-volumes", "VRC Light Volumes", "light volumes redsim avatar lighting voxel probes", 3, () => WPFMALightVolumesSection.Draw(s)),
                Tool("lightmap-uv", "Lightmap UV fixer", "lightmap uv blotchy black bake generate", 3, () => WPFMALightmapUvSection.Draw(s)),
                Tool("environment", "Environment presets", "sky skybox sun fog ambient day night sunset", 3, () => WPFMAEnvironmentSection.Draw(s)),
                Tool("texture-optimizer", "Texture optimizer", "textures compression crunch max size quest astc mipmaps", 4, () => WPFMATextureOptimizerSection.Draw(s)),
                Tool("occlusion", "Occlusion culling", "occlusion culling bake blocker walls", 4, () => WPFMAOcclusionSection.Draw(s)),
                Tool("draw-distance", "Draw-distance culling", "lod cull distance small props", 4, () => WPFMADrawDistanceSection.Draw(s)),
                Tool("heatmap", "Performance heatmap", "heatmap heat map heavy triangles materials texture memory overdraw transparent scene view colors", 4, () => WPFMAHeatmapSection.Draw(s)),
                Tool("material-merger", "Atlas maker (material merger)", "atlas merge materials draw calls batching posters pictures images one texture combine", 4, () => WPFMAMaterialMergerSection.Draw(s)),
                Tool("shader-swap", "Bulk shader swap", "shader swap materials mobile quest", 4, () => WPFMAShaderSwapSection.Draw(s)),
                Tool("editor-only", "Editor-only objects", "editoronly hide upload exclude", 4, () => WPFMAEditorOnlySection.Draw(s)),
                Tool("quest-switch", "Easy Quest Switch", "quest android pc switch platform eqs", 4, DrawQuestSwitch),
                Tool("fbx", "FBX exporter", "fbx export model blender", 5, DrawFbxExporterSection),
                Tool("package-creator", "Package creator", "unitypackage export package", 5, DrawPackageCreator),
                Tool("thumbnail", "Thumbnail studio", "thumbnail picture image upload photo text effects scene", 5, () => WPFMAThumbnailSection.Draw(s)),
                Tool("renamer", "Bulk renamer", "rename bulk batch names numbering prefix suffix find replace", 5, () => WPFMARenamerSection.Draw(s)),
                Tool("change-log", "Change log", "undo revert history snapshot restore changes", 5, () => WPFMAChangeLogSection.Draw(s))
            };
        }

        private static bool Matches(ToolEntry tool, string pageName, string[] terms)
        {
            string haystack = (tool.Title + " " + tool.Keywords + " " + pageName).ToLowerInvariant();
            return terms.All(term => haystack.Contains(term));
        }

        private void DrawToolsTab()
        {
            WPFMADiscordPresence.SetPanelState("Tools");

            // Not set up yet (the question was skipped or put off): ask here instead of quietly showing avatar tools.
            if (WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Undecided)
            {
                EditorGUILayout.Space(6f);
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.Space(8f);
                    using (new EditorGUILayout.VerticalScope(importerSectionStyle))
                    {
                        EditorGUILayout.LabelField("Is this an avatar project or a world project?", importerTitleStyle);
                        EditorGUILayout.LabelField(new GUIContent("Pick once; it installs what fits.", "WPFMA-SDK installs the VRChat SDK and tools that fit. You only choose once."), importerHintStyle);
                        EditorGUILayout.Space(4f);
                        using (new EditorGUILayout.HorizontalScope())
                        {
                            if (GUILayout.Button("Avatars", GUILayout.Height(28f)))
                            {
                                EditorApplication.delayCall += () => WPFMA.Editor.WPFMAInstaller.Choose(WPFMA.Editor.WPFMAInstaller.ProjectKind.Avatars);
                                GUIUtility.ExitGUI();
                            }
                            if (GUILayout.Button("Worlds", GUILayout.Height(28f)))
                            {
                                EditorApplication.delayCall += () => WPFMA.Editor.WPFMAInstaller.Choose(WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds);
                                GUIUtility.ExitGUI();
                            }
                        }
                    }
                    GUILayout.Space(8f);
                }
            }

            bool world = WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds;
            var pageNames = world ? WorldPageNames : ToolPageNames;
            string pageKey = world ? WPFMAWorldTypes.WorldPagePrefKey : ToolPagePrefKey;
            int page = Mathf.Clamp(EditorPrefs.GetInt(pageKey, 0), 0, pageNames.Length - 1);
            var tools = ToolList(world);

            EditorGUILayout.Space(4f);
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(8f);
                toolSearch = EditorGUILayout.TextField(toolSearch ?? string.Empty, EditorStyles.toolbarSearchField, GUILayout.Height(20f));
                if (!string.IsNullOrEmpty(toolSearch) && GUILayout.Button("Clear", EditorStyles.miniButton, GUILayout.Width(50f)))
                {
                    toolSearch = string.Empty;
                    GUI.FocusControl(null);
                }
                GUILayout.Space(8f);
            }

            string[] terms = (toolSearch ?? string.Empty).ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            bool searching = terms.Length > 0;

            if (!searching)
            {
                EditorGUILayout.Space(2f);
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.Space(8f);
                    using (new EditorGUILayout.VerticalScope())
                    {
                        int picked = DrawPageButtons(pageNames, page, pageNames.Length);
                        if (picked != page)
                        {
                            EditorPrefs.SetInt(pageKey, picked);
                            toolsScrollPosition = Vector2.zero;
                            page = picked;
                        }
                    }
                    GUILayout.Space(8f);
                }
            }

            if (WPFMA.Editor.WPFMAInstaller.PanelKindOverride != WPFMA.Editor.WPFMAInstaller.ProjectKind.Undecided)
            {
                var banner = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
                banner.x += 8f;
                banner.width -= 16f;
                EditorGUI.DrawRect(banner, new Color(0.45f, 0.3f, 0.05f));
                GUI.Label(banner, "  Dev preview: showing the " +
                                  (WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds ? "WORLD" : "AVATAR") +
                                  " tools. Change it in Tools > WPFMA-SDK Dev > Exporter.",
                    new GUIStyle(EditorStyles.miniBoldLabel) { normal = { textColor = Color.white } });
            }

            using (var scroll = new EditorGUILayout.ScrollViewScope(toolsScrollPosition))
            {
                toolsScrollPosition = scroll.scrollPosition;

                if (searching)
                {
                    var found = tools.Where(tool => Matches(tool, pageNames[Mathf.Clamp(tool.Page, 0, pageNames.Length - 1)], terms)).ToList();
                    if (found.Count == 0)
                    {
                        EditorGUILayout.Space(8f);
                        EditorGUILayout.LabelField("    No tools match '" + toolSearch + "'.", importerHintStyle);
                    }

                    int lastPage = -1;
                    foreach (var tool in found)
                    {
                        if (tool.Page != lastPage)
                        {
                            lastPage = tool.Page;
                            EditorGUILayout.Space(8f);
                            EditorGUILayout.LabelField("    " + pageNames[Mathf.Clamp(tool.Page, 0, pageNames.Length - 1)].ToUpperInvariant(), importerHintStyle);
                        }

                        if (IsToolHidden(tool.Id))
                            EditorGUILayout.LabelField("    (hidden on its page - turn it back on in Settings > Tools shown)", importerHintStyle);
                        tool.Draw();
                    }
                }
                else
                {
                    var shown = tools.Where(tool => tool.Page == page && !IsToolHidden(tool.Id)).ToList();
                    foreach (var tool in shown)
                        tool.Draw();

                    int hidden = tools.Count(tool => tool.Page == page && IsToolHidden(tool.Id));
                    if (hidden > 0)
                    {
                        EditorGUILayout.Space(8f);
                        EditorGUILayout.LabelField("    " + hidden + " tool(s) hidden on this page - Settings > Tools shown.", importerHintStyle);
                    }
                }

                EditorGUILayout.Space(10f);
            }
        }

        private void DrawToolsShownSettings()
        {
            bool world = WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds;
            var pageNames = world ? WorldPageNames : ToolPageNames;
            var tools = ToolList(world);

            EditorGUILayout.LabelField("Untick tools you never use to hide them from their page. Search still finds them. " +
                                       "Showing the " + (world ? "world" : "avatar") + " tools; the other side keeps its own list.",
                importerHintStyle);

            for (int p = 0; p < pageNames.Length; p++)
            {
                EditorGUILayout.Space(4f);
                EditorGUILayout.LabelField(pageNames[p], EditorStyles.boldLabel);
                foreach (var tool in tools.Where(x => x.Page == p))
                {
                    bool shown = !IsToolHidden(tool.Id);
                    bool now = EditorGUILayout.ToggleLeft(tool.Title, shown);
                    if (now != shown)
                        SetToolHidden(tool.Id, !now);
                }
            }

            EditorGUILayout.Space(4f);
            if (GUILayout.Button("Show every tool", GUILayout.Width(140f)))
            {
                foreach (var tool in ToolList(false).Concat(ToolList(true)))
                    SetToolHidden(tool.Id, false);
            }
        }

        private void DrawFbxExporterSection()
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(importerSectionStyle);

            try
            {
                var selectedObjects = Selection.gameObjects;
                if (DrawCollapsibleStrip("FBX exporter",
                        selectedObjects.Length == 0
                            ? "nothing selected"
                            : selectedObjects.Length + (selectedObjects.Length == 1 ? " object selected" : " objects selected"),
                        "WPFMA.Tools.FbxExpanded"))
                {
                    DrawFbxToolbar(selectedObjects);
                    DrawFbxSelection(selectedObjects);

                    if (fbxSettingsExpanded)
                        DrawFbxSettings();
                }
            }
            finally
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
            }
        }

        private bool questSwitchExpanded = true;

        private const string ModularAvatarPackagePath = "Packages/nadena.dev.modular-avatar";
        private const string SetupOutfitTypeName = "nadena.dev.modular_avatar.core.editor.SetupOutfit";

        private void DrawModularAvatar()
        {
            if (WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds)
                return;

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(importerSectionStyle);

            try
            {
                bool installed = Directory.Exists(ModularAvatarPackagePath) ||
                                 (Directory.Exists("Library/PackageCache") &&
                                  Directory.GetDirectories("Library/PackageCache", "nadena.dev.modular-avatar@*").Length > 0);

                if (!DrawCollapsibleStrip("Modular Avatar", installed ? "installed" : "not installed yet",
                        "WPFMA.Tools.ModularAvatarExpanded"))
                    return;

                if (!installed)
                {
                    EditorGUILayout.HelpBox(
                        "It ships with the SDK and installs on the next editor start. Reopen Unity if it does not appear.",
                        MessageType.Info);
                    return;
                }

                EditorGUILayout.LabelField(new GUIContent("Wear outfits without merging bones.", "Drop an outfit onto an avatar and wear it without merging bones by hand. Put the outfit " + "inside the avatar in the hierarchy, select the outfit, then press Setup Outfit."), importerHintStyle);

                var selected = Selection.activeGameObject;
                bool insideAvatar = selected != null && selected.transform.parent != null;
                bool looksLikeOutfit = insideAvatar && HasArmature(selected.transform);

                using (new EditorGUI.DisabledScope(!insideAvatar))
                {
                    if (DrawActionButton("Setup Outfit", 24f, GUILayout.Width(180f)))
                    {
                        var targets = Selection.gameObjects;

                        // Run after this repaint finishes. Modular Avatar opens its own
                        // window when something is wrong, and opening a window in the
                        // middle of our layout is what corrupts it.
                        EditorApplication.delayCall += () => RunSetupOutfit(targets);
                    }
                }

                EditorGUILayout.LabelField(
                    selected == null
                        ? "Select the outfit first."
                        : !insideAvatar
                            ? "'" + selected.name + "' is not inside anything. Drag it onto the avatar first."
                            : !looksLikeOutfit
                                ? "'" + selected.name + "' has no armature inside it, so it is probably not an outfit. " +
                                  "Select the outfit's top object - the one that contains its own Armature."
                                : "Will set up '" + selected.name + "'.",
                    new GUIStyle(importerHintStyle)
                    {
                        normal = { textColor = insideAvatar && !looksLikeOutfit ? WarnAmber : importerHintStyle.normal.textColor }
                    });

                EditorGUILayout.LabelField(new GUIContent("Modular Avatar by bd_ (MIT).", "Modular Avatar by bd_, MIT licence. Bundled unmodified; its components work anywhere in the " + "hierarchy and apply when you upload."), importerHintStyle);
            }
            finally
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
            }
        }

        private const string CompressorTypeName = "dev.limitex.avatar.compressor.TextureCompressor";

        private void DrawAvatarCompressor()
        {
            if (WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds)
                return;

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(importerSectionStyle);

            try
            {
                var type = FindTypeByName(CompressorTypeName);

                if (!DrawCollapsibleStrip("Avatar Compressor", type != null ? "installed" : "not installed yet",
                        "WPFMA.Tools.CompressorExpanded"))
                    return;

                if (type == null)
                {
                    string needs;
                    if (WPFMA.Editor.WPFMAInstaller.SkippedForUnity.TryGetValue("dev.limitex.avatar-compressor", out needs))
                        EditorGUILayout.HelpBox(
                            "It needs Unity " + needs + " or newer, and this project is on " + Application.unityVersion +
                            ". In the Creator Companion, change this project's Unity version to " + needs + " (the recommended one) to use it.",
                            MessageType.Warning);
                    else
                        EditorGUILayout.HelpBox(
                            "It ships with the SDK and installs on the next editor start. Reopen Unity if it does not appear.",
                            MessageType.Info);
                    return;
                }

                EditorGUILayout.LabelField(new GUIContent("Smaller textures at upload.", "Shrinks textures when you upload, without touching the originals. Put it on the avatar once " + "and every upload after that is smaller."), importerHintStyle);

                var avatar = AvatarRoot(Selection.activeGameObject);
                var existing = avatar != null ? avatar.GetComponent(type) : null;

                if (avatar == null)
                {
                    EditorGUILayout.LabelField("Select the avatar, or anything inside it.", importerHintStyle);
                }
                else if (existing != null)
                {
                    EditorGUILayout.LabelField("Already on '" + avatar.name + "'.", importerHintStyle);
                    if (DrawActionButton("Show its settings", 22f, GUILayout.Width(180f)))
                        Selection.activeObject = existing;
                }
                else if (DrawActionButton("Add to " + avatar.name, 24f, GUILayout.Width(220f)))
                {
                    var added = Undo.AddComponent(avatar, type);
                    Selection.activeObject = added;
                }

                EditorGUILayout.LabelField(new GUIContent("Avatar Compressor by Limitex (MIT).", "Avatar Compressor by Limitex, MIT licence. Bundled unmodified."), importerHintStyle);
            }
            finally
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
            }
        }

        private static GameObject AvatarRoot(GameObject from)
        {
            var current = from != null ? from.transform : null;
            while (current != null)
            {
                foreach (var component in current.GetComponents<Component>())
                {
                    if (component != null && component.GetType().Name == "VRCAvatarDescriptor")
                        return current.gameObject;
                }

                current = current.parent;
            }

            return null;
        }

        private static Type FindTypeByName(string name)
        {
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    var found = assembly.GetType(name, false);
                    if (found != null)
                        return found;
                }
                catch (Exception)
                {
                }
            }

            return null;
        }

        private static void RunSetupOutfit(GameObject[] targets)
        {
            System.Reflection.MethodInfo method = null;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                Type type;
                try
                {
                    type = assembly.GetType(SetupOutfitTypeName, false);
                }
                catch (Exception)
                {
                    continue;
                }

                if (type == null)
                    continue;

                method = type.GetMethod("SetupOutfitUI",
                    System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static,
                    null, new[] { typeof(GameObject) }, null);
                break;
            }

            if (method == null)
            {
                Debug.LogWarning("[WPFMA-SDK] Modular Avatar's Setup Outfit could not be found. It may still be compiling.");
                return;
            }

            foreach (var target in targets)
            {
                if (target == null)
                    continue;

                try
                {
                    method.Invoke(null, new object[] { target });
                }
                catch (System.Reflection.TargetInvocationException e)
                {
                    Debug.LogWarning("[WPFMA-SDK] Setup Outfit failed on '" + target.name + "': " +
                                     (e.InnerException != null ? e.InnerException.Message : e.Message));
                }
            }
        }

        private static bool HasArmature(Transform root)
        {
            foreach (var child in root.GetComponentsInChildren<Transform>(true))
            {
                if (child == root)
                    continue;

                string name = child.name.ToLowerInvariant();
                if (name.Contains("armature") || name.Contains("hips"))
                    return true;
            }

            return root.GetComponentInChildren<SkinnedMeshRenderer>(true) is var skinned && skinned != null &&
                   skinned.bones != null && skinned.bones.Length > 0 && skinned.rootBone != null &&
                   skinned.rootBone.IsChildOf(root);
        }

        private const string QuestSwitchPackagePath = "Packages/vrchat.jordo.easyquestswitch";
        private const string QuestSwitchMenuItem = "Window/Easy Quest Switch";

        private void DrawQuestSwitch()
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(importerSectionStyle);

            try
            {
                bool available = WPFMAQuestSwitchHost.IsInstalled;
                questSwitchExpanded = DrawCollapsibleStrip("Easy Quest Switch",
                    available ? "built in" : WPFMAQuestSwitchHost.IsPendingImport() ? "importing" : "not installed yet",
                    "WPFMA.Tools.QuestSwitchExpanded");

                if (!questSwitchExpanded)
                    return;

                EditorGUILayout.LabelField(new GUIContent("Auto-switches components for PC and Quest.", "Changes components automatically when you switch between PC and Android, so a world or " + "avatar does not have to be set up twice."), importerHintStyle);

                if (!available)
                {
                    EditorGUILayout.HelpBox(
                        WPFMAQuestSwitchHost.IsPendingImport()
                            ? "The package is in place and Unity is still compiling it. It appears here once that finishes."
                            : "It ships with the SDK and installs on the next editor start. Reopen Unity if it does not appear.",
                        MessageType.Info);
                }

                EditorGUILayout.LabelField(new GUIContent("EasyQuestSwitch © 2020 Jordo (BSD 3-Clause).", "EasyQuestSwitch © 2020 Jordo, BSD 3-Clause with an added no-fee clause. " + "Bundled unmodified; see LICENSE inside the package."), importerHintStyle);

                if (available && WPFMAQuestSwitchHost.Failure != null)
                {
                    EditorGUILayout.HelpBox(
                        "Could not show it here: " + WPFMAQuestSwitchHost.Failure,
                        MessageType.Warning);

                    using (new EditorGUILayout.HorizontalScope())
                    {
                        if (DrawActionButton("Open its own window", 22f, GUILayout.Width(180f)))
                            EditorApplication.ExecuteMenuItem(QuestSwitchMenuItem);

                        if (GUILayout.Button("Try again", importerToolbarButtonStyle, GUILayout.Width(90f), GUILayout.Height(22f)))
                            WPFMAQuestSwitchHost.Reset();
                    }
                }
            }
            finally
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
            }

            if (questSwitchExpanded && WPFMAQuestSwitchHost.IsInstalled && WPFMAQuestSwitchHost.Failure == null)
                WPFMAQuestSwitchHost.Draw();
        }

        private void DrawPackageCreator()
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(8f);
            EditorGUILayout.BeginVertical(importerSectionStyle);

            try
            {
                if (packageAvatar == null && Selection.activeGameObject != null)
                    packageAvatar = Selection.activeGameObject;

                if (packagePlan == null || packagePlan.Avatar != packageAvatar)
                {
                    packagePlan = WPFMAPackageBuilder.Scan(packageAvatar);
                    packageStatus = null;
                }

                if (DrawCollapsibleStrip("Package creator",
                        packagePlan.Usable ? FormatBytes(packagePlan.Bytes) + " of assets" : "no avatar",
                        "WPFMA.Tools.PackageCreatorExpanded"))
                {
                    DrawPackageToolbar();
                    DrawPackageContents();
                }
            }
            finally
            {
                EditorGUILayout.EndVertical();
                GUILayout.Space(8f);
                EditorGUILayout.EndHorizontal();
            }
        }

        private void DrawPackageToolbar()
        {
            var rect = GUILayoutUtility.GetRect(0f, 28f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.yMax - 1f, rect.width, 1f), ToolbarEdge);

            float top = rect.y + 4f;
            const float height = 20f;
            float x = rect.x + 6f;

            float buildWidth = ButtonWidth(accentButtonStyle, "Create package", 20f);
            using (new EditorGUI.DisabledScope(!packagePlan.Usable))
            {
                if (GUI.Button(new Rect(x, top, buildWidth, height), "Create package", accentButtonStyle))
                {
                    string message;
                    WPFMAPackageBuilder.Build(packagePlan, packageIncludeScene, out message);
                    packageStatus = message;
                    AssetDatabase.Refresh();
                }
            }

            x += buildWidth + 8f;

            float toggleWidth = GUI.skin.label.CalcSize(new GUIContent("with scene")).x + 22f;
            packageIncludeScene = GUI.Toggle(new Rect(x, top + 1f, toggleWidth, 17f), packageIncludeScene, "with scene",
                new GUIStyle(EditorStyles.toggle) { fontSize = 11 });
            x += toggleWidth + 8f;

            float fieldWidth = Mathf.Min(220f, rect.xMax - ScrollbarGutter - x - 4f);
            if (fieldWidth < 80f)
                return;

            var fieldRect = new Rect(rect.xMax - ScrollbarGutter - fieldWidth - 4f, top, fieldWidth, height);
            var picked = (GameObject)EditorGUI.ObjectField(fieldRect, packageAvatar, typeof(GameObject), true);
            if (picked != packageAvatar)
            {
                packageAvatar = picked;
                packagePlan = WPFMAPackageBuilder.Scan(packageAvatar);
                packageStatus = null;
            }
        }

        private void DrawPackageContents()
        {
            if (packagePlan == null)
                return;

            if (!packagePlan.Usable)
            {
                DrawVpmEmptyRow(packagePlan.Problem);
                return;
            }

            int index = 0;
            foreach (var pair in packagePlan.Breakdown)
            {
                var row = GUILayoutUtility.GetRect(0f, 22f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(row, index++ % 2 == 0 ? RowOdd : RowEven);

                float right = row.xMax - ScrollbarGutter - 4f;
                GUI.Label(new Rect(right - 70f, row.y, 66f, row.height), pair.Value.ToString(),
                    new GUIStyle(importerMetaStyle) { normal = { textColor = MetaText } });
                GUI.Label(new Rect(row.x + 8f, row.y, Mathf.Max(60f, right - row.x - 80f), row.height), pair.Key,
                    importerRowNameStyle);
            }

            if (packagePlan.PackageRequirements.Count > 0)
            {
                DrawVpmSectionLabel("Recipient must install these first");
                foreach (var requirement in packagePlan.PackageRequirements)
                {
                    var row = GUILayoutUtility.GetRect(0f, 22f, GUILayout.ExpandWidth(true));
                    EditorGUI.DrawRect(row, index++ % 2 == 0 ? RowOdd : RowEven);
                    GUI.Label(new Rect(row.x + 8f, row.y, row.width - 16f, row.height), requirement,
                        new GUIStyle(importerRowNameStyle) { fontSize = 11, normal = { textColor = WarnAmber } });
                }
            }

            var footer = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(new Rect(footer.x, footer.y, footer.width, 1f), Separator);
            GUI.Label(new Rect(footer.x + 8f, footer.y, footer.width - 16f, footer.height),
                packageStatus ?? (packagePlan.AssetPaths.Count + " asset(s) will be packed from " + packagePlan.PrefabPath),
                new GUIStyle(importerRowNameStyle)
                {
                    fontSize = 11,
                    normal = { textColor = packageStatus != null ? OkGreen : FaintText }
                });
        }

        private void DrawSafetySettings()
        {
            bool badges = WPFMASafety.ListBadges;
            bool editedBadges = EditorGUILayout.ToggleLeft(new GUIContent("Check packages in the Import list automatically",
                "Shows clean / DLLs / dangerous next to each package. Packages are still checked when you import them."), badges);
            if (editedBadges != badges)
                WPFMASafety.ListBadges = editedBadges;

            EditorGUILayout.LabelField(new GUIContent("Import list packages are checked first.", "Packages from the Import list are checked for DLLs and token loggers before they're imported."), importerHintStyle);

            bool guard = WPFMASafety.GuardOn;
            bool editedGuard = EditorGUILayout.ToggleLeft(new GUIContent("Check new scripts and DLLs as they come in",
                "Also catches packages you double-click, or files you copy in. Anything that looks like a token logger is moved to WPFMA-Quarantine for you to accept or deny."), guard);
            if (editedGuard != guard)
                WPFMASafety.GuardOn = editedGuard;

            using (new EditorGUI.DisabledScope(!editedGuard))
            {
                bool hold = WPFMASafety.HoldRisky;
                bool editedHold = EditorGUILayout.ToggleLeft(new GUIContent("Hold new DLLs until I say they're OK",
                    "New DLLs (and scripts that do risky things) wait in WPFMA-Quarantine until you accept or deny them. Dangerous files are always held."), hold);
                if (editedHold != hold)
                    WPFMASafety.HoldRisky = editedHold;
            }

            EditorGUILayout.BeginHorizontal();
            int quarantined = WPFMASafety.Quarantined().Count;
            EditorGUILayout.LabelField(quarantined == 0 ? "Nothing in quarantine." : quarantined + (quarantined == 1 ? " file" : " files") + " in quarantine.", importerHintStyle);
            if (GUILayout.Button("Open", GUILayout.Width(70f)))
            {
                WPFMASafetyWindow.ShowQuarantine();
                GUIUtility.ExitGUI();
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            int trustedCount = WPFMASafety.TrustedCount;
            EditorGUILayout.LabelField(trustedCount == 0 ? "No files trusted yet." : trustedCount + (trustedCount == 1 ? " file" : " files") + " you said were OK.", importerHintStyle);
            using (new EditorGUI.DisabledScope(trustedCount == 0))
            {
                if (GUILayout.Button("Forget", GUILayout.Width(70f)) &&
                    EditorUtility.DisplayDialog("Forget trusted files?", "DLLs you said were OK will be checked and held back again next time they arrive.", "Forget", "Cancel"))
                    WPFMASafety.ForgetTrusted();
            }
            EditorGUILayout.EndHorizontal();

            if (GUILayout.Button("Check this project now"))
            {
                WPFMASafetyWindow.ShowProject(WPFMASafety.CheckProject());
                GUIUtility.ExitGUI();
            }
        }

        private bool DrawCollapsibleStrip(string title, string detail, string prefKey, bool defaultExpanded = true)
        {
            bool expanded = EditorPrefs.GetBool(prefKey, defaultExpanded);

            var rect = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), ToolbarEdge);

            GUI.Label(new Rect(rect.x + 8f, rect.y, 14f, rect.height), expanded ? "\u25be" : "\u25b8",
                new GUIStyle(importerRowNameStyle) { normal = { textColor = AccentBlue } });

            GUI.Label(new Rect(rect.x + 24f, rect.y, 240f, rect.height), title,
                new GUIStyle(importerRowNameStyle) { normal = { textColor = AccentBlue } });

            if (!string.IsNullOrEmpty(detail))
                GUI.Label(new Rect(rect.xMax - ScrollbarGutter - 204f, rect.y, 200f, rect.height), detail,
                    new GUIStyle(importerMetaStyle) { normal = { textColor = FaintText } });

            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);

            var evt = Event.current;
            if (evt.type == EventType.MouseDown && evt.button == 0 && rect.Contains(evt.mousePosition))
            {
                expanded = !expanded;
                EditorPrefs.SetBool(prefKey, expanded);
                evt.Use();
                Repaint();
            }

            return expanded;
        }

        private void DrawSectionStrip(string title, string detail)
        {
            var rect = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), ToolbarEdge);

            GUI.Label(new Rect(rect.x + 8f, rect.y, 240f, rect.height), title,
                new GUIStyle(importerRowNameStyle) { normal = { textColor = AccentBlue } });

            if (!string.IsNullOrEmpty(detail))
                GUI.Label(new Rect(rect.xMax - ScrollbarGutter - 204f, rect.y, 200f, rect.height), detail,
                    new GUIStyle(importerMetaStyle) { normal = { textColor = FaintText } });
        }

        private void DrawFbxToolbar(GameObject[] selectedObjects)
        {
            var rect = GUILayoutUtility.GetRect(0f, 28f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.yMax - 1f, rect.width, 1f), ToolbarEdge);

            float top = rect.y + 4f;
            const float height = 20f;
            float x = rect.x + 6f;

            float exportWidth = ButtonWidth(accentButtonStyle, "Export selected", 20f);
            using (new EditorGUI.DisabledScope(selectedObjects.Length == 0))
            {
                if (GUI.Button(new Rect(x, top, exportWidth, height), "Export selected", accentButtonStyle))
                    ExportSelectedToFbx(selectedObjects);
            }

            x += exportWidth + 5f;
            float settingsWidth = ButtonWidth(importerToolbarButtonStyle, "Settings");
            if (GUI.Button(new Rect(x, top, settingsWidth, height), "Settings", importerToolbarButtonStyle))
                fbxSettingsExpanded = !fbxSettingsExpanded;

            x += settingsWidth + 8f;

            var revealRect = new Rect(rect.xMax - ScrollbarGutter - 26f, top, 24f, height);
            if (GUI.Button(revealRect, "\u2197", importerToolbarButtonStyle))
            {
                Directory.CreateDirectory(FbxExportFolder);
                EditorUtility.RevealInFinder(Path.GetFullPath(FbxExportFolder));
            }

            float nameWidth = Mathf.Min(200f, revealRect.x - x - 82f);
            if (nameWidth < 60f)
                return;

            var nameRect = new Rect(revealRect.x - nameWidth - 4f, top, nameWidth, height);
            GUI.Label(new Rect(nameRect.x - 78f, rect.y, 74f, rect.height), "export name",
                new GUIStyle(importerMetaStyle) { normal = { textColor = FaintText } });
            fbxExportName = EditorGUI.TextField(nameRect, fbxExportName);
        }

        private void DrawFbxSelection(GameObject[] selectedObjects)
        {
            if (selectedObjects.Length == 0)
            {
                var empty = GUILayoutUtility.GetRect(0f, 22f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(empty, RowEven);
                GUI.Label(new Rect(empty.x + 8f, empty.y, empty.width - 16f, empty.height),
                    "Select one or more GameObjects in the Hierarchy or Project window.",
                    new GUIStyle(importerRowNameStyle) { fontSize = 11, normal = { textColor = DimText } });
                return;
            }

            for (int i = 0; i < selectedObjects.Length; i++)
            {
                var selected = selectedObjects[i];
                if (selected == null)
                    continue;

                var row = GUILayoutUtility.GetRect(0f, 22f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(row, i % 2 == 0 ? RowOdd : RowEven);

                float right = row.xMax - ScrollbarGutter - 4f;
                int children = selected.transform.childCount;
                GUI.Label(new Rect(right - 110f, row.y, 106f, row.height),
                    children == 1 ? "1 child" : children + " children",
                    new GUIStyle(importerMetaStyle) { normal = { textColor = DimText } });

                GUI.Label(new Rect(row.x + 8f, row.y, Mathf.Max(60f, right - row.x - 120f), row.height),
                    selected.name, importerRowNameStyle);
            }

            var target = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(new Rect(target.x, target.y, target.width, 1f), Separator);
            GUI.Label(new Rect(target.x + 8f, target.y, target.width - 16f, target.height),
                "exports to " + FbxExportFolder,
                new GUIStyle(importerRowNameStyle) { fontSize = 11, normal = { textColor = FaintText } });
        }

        private void DrawFbxSettings()
        {
            object settings = GetFbxSettingsInfo();
            if (settings == null)
            {
                EditorGUILayout.HelpBox("The FBX Exporter settings are unavailable. Make sure the package is installed.", MessageType.Warning);
                return;
            }

            EditorGUI.indentLevel++;
            DrawFbxPopup(settings, "Export Format", "ExportFormat", new[] { "ASCII", "Binary" });
            DrawFbxPopup(settings, "Include", "ModelAnimIncludeOption", new[] { "Model(s) Only", "Animation Only", "Model(s) + Animation" });

            int include = GetFbxEnumValue(settings, "ModelAnimIncludeOption");
            using (new EditorGUI.DisabledScope(include == 1))
            {
                DrawFbxPopup(settings, "LOD level", "LODExportType", new[] { "All Levels", "Highest", "Lowest" });
                DrawFbxPopup(settings, "Object(s) Position", "ObjectPosition", new[] { "Local Pivot", "World Absolute" });
                DrawFbxToggle(settings, "Export Unrendered", "ExportUnredererd");
            }

            using (new EditorGUI.DisabledScope(include == 0))
                DrawFbxToggle(settings, "Animated Skinned Mesh", "SetAnimatedSkinnedMesh");

            DrawFbxToggle(settings, "Compatible Naming", "SetUseMayaCompatibleNames");
            using (new EditorGUI.DisabledScope(!IsExportInsideProject()))
                DrawFbxToggle(settings, "Preserve Import Settings", "SetPreserveImportSettings");
            DrawFbxToggle(settings, "Keep Instances", "SetKeepInstances");
            DrawFbxToggle(settings, "Embed Textures", "SetEmbedTextures");
            fbxHumanoid = EditorGUILayout.ToggleLeft("Humanoid", fbxHumanoid);

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField("Transfer Animation", EditorStyles.boldLabel);
            fbxAnimationSource = (Transform)EditorGUILayout.ObjectField("Source", fbxAnimationSource, typeof(Transform), true);
            fbxAnimationDestination = (Transform)EditorGUILayout.ObjectField("Destination", fbxAnimationDestination, typeof(Transform), true);
            InvokeFbxSetter(settings, "SetAnimationSource", fbxAnimationSource);
            InvokeFbxSetter(settings, "SetAnimationDest", fbxAnimationDestination);
            EditorGUI.indentLevel--;
        }

        private static object GetFbxSettingsInfo()
        {
            var exporterType = GetFbxExporterType();
            var settingsType = exporterType?.Assembly.GetType("UnityEditor.Formats.Fbx.Exporter.ExportSettings");
            if (settingsType == null)
                return null;

            var instanceProperty = settingsType.GetProperty("instance", BindingFlags.Public | BindingFlags.Static);
            var instance = instanceProperty?.GetValue(null, null);
            if (instance == null)
                return null;

            var modelSettingsProperty = settingsType.GetProperty("ExportModelSettings", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            var modelSettings = modelSettingsProperty?.GetValue(instance, null);
            if (modelSettings == null)
                return null;

            return modelSettings?.GetType().GetProperty("info", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(modelSettings, null);
        }

        private static Type GetFbxExporterType()
        {
            var assembly = AppDomain.CurrentDomain.GetAssemblies()
                .FirstOrDefault(candidate => candidate.GetName().Name == FbxEditorAssemblyName);
            return assembly?.GetType(FbxModelExporterTypeName);
        }

        private static int GetFbxEnumValue(object settings, string propertyName)
        {
            var property = settings.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            return property == null ? 0 : Convert.ToInt32(property.GetValue(settings, null));
        }

        private static bool GetFbxBoolValue(object settings, string setterName)
        {
            string propertyName = setterName == "SetAnimatedSkinnedMesh" ? "AnimateSkinnedMesh" :
                setterName == "SetExportUnredererd" ? "ExportUnrendered" : setterName.Substring(3);
            var property = settings.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            return property != null && (bool)property.GetValue(settings, null);
        }

        private void DrawFbxPopup(object settings, string label, string propertyName, string[] options)
        {
            int current = GetFbxEnumValue(settings, propertyName);
            int updated = EditorGUILayout.Popup(label, current, options);
            if (updated != current)
            {
                var property = settings.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                var setterName = propertyName == "ExportFormat" ? "SetExportFormat" :
                    propertyName == "ModelAnimIncludeOption" ? "SetModelAnimIncludeOption" :
                    propertyName == "LODExportType" ? "SetLODExportType" : "SetObjectPosition";
                InvokeFbxSetter(settings, setterName, Enum.ToObject(property.PropertyType, updated));
            }
        }

        private static void DrawFbxToggle(object settings, string label, string setterName)
        {
            bool current = GetFbxBoolValue(settings, setterName);
            bool updated = EditorGUILayout.ToggleLeft(label, current);
            if (updated != current)
                InvokeFbxSetter(settings, setterName, updated);
        }

        private static void InvokeFbxSetter(object settings, string setterName, object value)
        {
            if (settings == null)
                return;

            var methods = settings.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            var method = methods.FirstOrDefault(candidate =>
            {
                if (candidate.Name != setterName)
                    return false;

                var parameters = candidate.GetParameters();
                return parameters.Length == 1 && (value == null || parameters[0].ParameterType.IsInstanceOfType(value));
            });
            if (method == null)
                return;

            method.Invoke(settings, new[] { value });
        }

        private bool IsExportInsideProject()
        {
            return true;
        }

        private void ExportSelectedToFbx(GameObject[] selectedObjects)
        {
            string exportName = string.IsNullOrWhiteSpace(fbxExportName) ? "ExportedModel" : fbxExportName.Trim();
            exportName = SanitizeFbxFileName(exportName);
            Directory.CreateDirectory(FbxExportFolder);
            string assetPath = AssetDatabase.GenerateUniqueAssetPath(FbxExportFolder + "/" + exportName + ".fbx");
            string path = Path.GetFullPath(assetPath);

            var objectsToExport = GetFbxExportRoots(selectedObjects)
                .Cast<UnityEngine.Object>()
                .ToArray();

            try
            {
                WPFMADiscordPresence.SetBusyState("Preparing FBX export", 10d);
                var exporterType = GetFbxExporterType();
                var exportMethod = exporterType?.GetMethod(
                    "ExportObjects",
                    BindingFlags.Public | BindingFlags.Static,
                    null,
                    new[] { typeof(string), typeof(UnityEngine.Object[]) },
                    null);
                if (exportMethod == null)
                {
                    EditorUtility.DisplayDialog("FBX Exporter not found", "Install the Unity FBX Exporter package before exporting.", "OK");
                    return;
                }

                WPFMADiscordPresence.SetBusyState("Exporting FBX", 10d);
                string exportedPath;
                try
                {
                    exportedPath = exportMethod.Invoke(null, new object[] { path, objectsToExport }) as string;
                }
                catch (TargetInvocationException exception)
                {
                    HandleFbxExportException(path, exception.InnerException ?? exception);
                    return;
                }
                catch (Exception exception)
                {
                    HandleFbxExportException(path, exception);
                    return;
                }

                if (!string.IsNullOrEmpty(exportedPath))
                {
                    AssetDatabase.Refresh();
                    if (fbxHumanoid)
                    {
                        WPFMADiscordPresence.SetBusyState("Applying Humanoid import settings", 10d);
                        SetFbxHumanoidImportSettings(assetPath);
                    }
                }
                else
                {
                    EditorUtility.DisplayDialog("FBX export failed", "The FBX Exporter did not create a file.", "OK");
                }
            }
            finally
            {
                WPFMADiscordPresence.ClearBusyState();
            }
        }

        private static void HandleFbxExportException(string path, Exception exception)
        {
            if (File.Exists(path))
                File.Delete(path);

            Debug.LogException(exception);
            EditorUtility.DisplayDialog(
                "FBX export failed",
                "The FBX Exporter could not export this hierarchy. Make sure the avatar root and its complete armature are selected, then try again. See the Console for the detailed exporter error.",
                "OK");
        }

        private static IEnumerable<GameObject> GetFbxExportRoots(GameObject[] selectedObjects)
        {
            var exportRoots = new HashSet<Transform>();
            foreach (var selectedObject in selectedObjects)
            {
                Transform exportRoot = selectedObject.transform;
                var skinnedMeshes = selectedObject.GetComponentsInChildren<SkinnedMeshRenderer>(true);
                foreach (var skinnedMesh in skinnedMeshes)
                {
                    if (skinnedMesh == null)
                        continue;

                    exportRoot = FindCommonAncestor(exportRoot, skinnedMesh.transform);
                    foreach (var bone in skinnedMesh.bones)
                    {
                        if (bone != null)
                            exportRoot = FindCommonAncestor(exportRoot, bone);
                    }
                }

                exportRoots.Add(exportRoot);
            }

            return exportRoots.Select(root => root.gameObject);
        }

        private static Transform FindCommonAncestor(Transform first, Transform second)
        {
            if (first == null)
                return second;
            if (second == null)
                return first;

            var ancestors = new HashSet<Transform>();
            for (var current = first; current != null; current = current.parent)
                ancestors.Add(current);

            for (var current = second; current != null; current = current.parent)
            {
                if (ancestors.Contains(current))
                    return current;
            }

            return first.root;
        }

        private static string SanitizeFbxFileName(string fileName)
        {
            return string.IsNullOrWhiteSpace(fileName) ? "ExportedModel" : WPFMAPaths.SafeFileName(fileName);
        }

        private static void SetFbxHumanoidImportSettings(string exportedPath)
        {
            string normalizedPath = exportedPath.Replace('\\', '/');
            string assetPath = normalizedPath.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase)
                ? normalizedPath
                : FileUtil.GetProjectRelativePath(Path.GetFullPath(exportedPath));
            if (!string.IsNullOrEmpty(assetPath))
                assetPath = assetPath.Replace('\\', '/');
            if (string.IsNullOrEmpty(assetPath) || !assetPath.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
            {
                EditorUtility.DisplayDialog("Humanoid import unavailable", "Humanoid can only be applied to an FBX exported inside the project's Assets folder.", "OK");
                return;
            }

            AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
            var importer = AssetImporter.GetAtPath(assetPath) as ModelImporter;
            if (importer == null)
            {
                EditorUtility.DisplayDialog("Humanoid import failed", "Unity could not find the generated FBX importer.", "OK");
                return;
            }

            importer.animationType = ModelImporterAnimationType.Human;
            importer.SaveAndReimport();
        }

        private static void OpenCreatorPanel()
        {
            foreach (var editorWindow in Resources.FindObjectsOfTypeAll<EditorWindow>())
            {
                if (editorWindow.GetType().Name == "VRCSdkControlPanel")
                    editorWindow.Close();
            }

            WPFMAControlPanelTheme.ShowControlPanel();
        }

        private struct PackageEntry
        {
            public string Path;
            public string Name;
            public long Bytes;
            public DateTime Added;
        }

        private const string ImportedPrefPrefix = "WPFMA.Importer.Imported.";

        private PackageEntry[] GetFilteredPackages(out int totalCount, out long totalBytes)
        {
            var all = new List<PackageEntry>();
            totalBytes = 0L;

            foreach (var path in GetPackages())
            {
                var info = new FileInfo(path);
                all.Add(new PackageEntry
                {
                    Path = path,
                    Name = Path.GetFileNameWithoutExtension(path),
                    Bytes = info.Exists ? info.Length : 0L,
                    Added = info.Exists ? info.LastWriteTime : DateTime.MinValue
                });
                totalBytes += info.Exists ? info.Length : 0L;
            }

            totalCount = all.Count;

            if (!string.IsNullOrEmpty(importerFilter))
                all = all.Where(e => e.Name.IndexOf(importerFilter, StringComparison.OrdinalIgnoreCase) >= 0).ToList();

            return all.OrderBy(e => e.Name, StringComparer.OrdinalIgnoreCase).ToArray();
        }

        private void DrawImporterToolbar()
        {
            var rect = GUILayoutUtility.GetRect(0f, 28f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.yMax - 1f, rect.width, 1f), ToolbarEdge);

            float top = rect.y + 4f;
            const float height = 20f;
            float x = rect.x + 6f;

            float width = ButtonWidth(importerToolbarButtonStyle, "Open folder");
            if (GUI.Button(new Rect(x, top, width, height), "Open folder", importerToolbarButtonStyle))
                OpenImportFolder();
            x += width + 5f;

            width = ButtonWidth(importerToolbarButtonStyle, "Refresh");
            if (GUI.Button(new Rect(x, top, width, height), "Refresh", importerToolbarButtonStyle))
            {
                AssetDatabase.Refresh();
                Repaint();
            }

            x += width + 5f;
            width = ButtonWidth(importerToolbarButtonStyle, "Export");
            if (GUI.Button(new Rect(x, top, width, height), "Export", importerToolbarButtonStyle))
                ExportImports();

            x += width + 5f;
            width = ButtonWidth(importerToolbarButtonStyle, "Check ▾");
            var checkRect = new Rect(x, top, width, height);
            if (GUI.Button(checkRect, new GUIContent("Check ▾", "Look for DLLs and token loggers"), importerToolbarButtonStyle))
            {
                var menu = new GenericMenu();
                menu.AddItem(new GUIContent("Check a package..."), false, () =>
                {
                    string picked = EditorUtility.OpenFilePanel("Check a package", string.Empty, "unitypackage");
                    if (string.IsNullOrEmpty(picked))
                        return;
                    var checkedReport = WPFMASafety.CheckNow(picked);
                    WPFMASafetyWindow.ShowPackage(checkedReport, choice => WPFMASafety.ImportChoice(checkedReport, picked, true, choice));
                });
                menu.AddItem(new GUIContent("Check this project"), false, () => WPFMASafetyWindow.ShowProject(WPFMASafety.CheckProject()));
                menu.AddSeparator(string.Empty);
                menu.AddItem(new GUIContent("Quarantine..."), false, WPFMASafetyWindow.ShowQuarantine);
                menu.DropDown(checkRect);
            }

            x += width + 8f;
            float searchRight = rect.xMax - ScrollbarGutter;
            float searchWidth = Mathf.Min(180f, searchRight - x);
            if (searchWidth >= 80f)
                importerFilter = EditorGUI.TextField(new Rect(searchRight - searchWidth, top, searchWidth, height),
                    importerFilter, EditorStyles.toolbarSearchField);
        }

        private void DrawImporterSummary(int totalCount, long totalBytes)
        {
            var rect = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
            var titleStyle = new GUIStyle(importerRowNameStyle) { normal = { textColor = AccentBlue } };
            GUI.Label(new Rect(rect.x + 4f, rect.y, 60f, rect.height), "Import", titleStyle);

            var pathStyle = new GUIStyle(importerPathStyle) { normal = { textColor = FaintText } };
            GUI.Label(new Rect(rect.x + 50f, rect.y, rect.width - 200f, rect.height), ImportFolderPath, pathStyle);

            string summary = totalCount + (totalCount == 1 ? " package, " : " packages, ") + FormatBytes(totalBytes);
            GUI.Label(new Rect(rect.xMax - 164f - ScrollbarGutter, rect.y, 160f, rect.height), summary,
                new GUIStyle(importerMetaStyle) { normal = { textColor = FaintText } });
        }

        private void DrawImporterList(PackageEntry[] packages)
        {
            const float rowHeight = 24f;
            var listRect = GUILayoutUtility.GetRect(0f, Mathf.Max(rowHeight, packages.Length * rowHeight),
                GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(new Rect(listRect.x, listRect.y, listRect.width, 1f), Separator);

            if (packages.Length == 0)
            {
                GUI.Label(new Rect(listRect.x + 8f, listRect.y, listRect.width, rowHeight),
                    string.IsNullOrEmpty(importerFilter) ? "No .unitypackage files in the folder." : "Nothing matches that filter.",
                    new GUIStyle(importerRowNameStyle) { normal = { textColor = DimText } });
            }

            string importing = WPFMAPackageImportQueue.IsProcessing ? WPFMAPackageImportQueue.GetCurrentPackageName() : null;

            for (int i = 0; i < packages.Length; i++)
            {
                var entry = packages[i];
                var row = new Rect(listRect.x, listRect.y + i * rowHeight, listRect.width, rowHeight);
                bool selected = importerSelection.Contains(entry.Path);
                EditorGUI.DrawRect(row, selected ? RowSelected : (i % 2 == 0 ? RowOdd : RowEven));

                var toggleRect = new Rect(row.x + 7f, row.y + 5f, 14f, 14f);
                if (GUI.Toggle(toggleRect, selected, GUIContent.none) != selected)
                {
                    if (selected) importerSelection.Remove(entry.Path);
                    else importerSelection.Add(entry.Path);
                }

                bool isImporting = importing != null && importing == entry.Name;
                bool wasImported = EditorPrefs.HasKey(ImportedPrefPrefix + entry.Name);

                // Columns from the right: Import, date, size, safety badge; the name gets what's left.
                // When narrow, the date goes first so the name stays readable.
                float buttonWidth = ButtonWidth(accentButtonStyle, "Import", 20f);
                float right = row.xMax - ScrollbarGutter - 4f;
                const float gap = 6f, dateWidth = 64f, sizeWidth = 64f, badgeWidth = 72f;
                float nameLeft = row.x + 28f;
                bool showDate = right - buttonWidth - gap - dateWidth - gap - sizeWidth - gap - badgeWidth - gap - nameLeft >= 120f;
                float dateX = right - buttonWidth - gap - dateWidth;
                float sizeX = (showDate ? dateX : right - buttonWidth) - gap - sizeWidth;
                float badgeX = sizeX - gap - badgeWidth;
                float nameWidth = Mathf.Max(40f, badgeX - gap - nameLeft);
                var nameRect = new Rect(nameLeft, row.y, nameWidth, row.height);
                var nameStyle = new GUIStyle(importerRowNameStyle) { clipping = TextClipping.Clip };
                if (isImporting) nameStyle.normal.textColor = WPFMATheme.Shift(new Color(0.79f, 0.83f, 0.87f));
                else if (wasImported) nameStyle.normal.textColor = DimText;
                GUI.Label(nameRect, new GUIContent(entry.Name, entry.Name), nameStyle);

                if (isImporting)
                {
                    var barRect = new Rect(nameRect.xMax + 8f, row.y + 10f, Mathf.Max(20f, right - nameRect.xMax - 90f), 5f);
                    EditorGUI.DrawRect(barRect, WPFMATheme.Shift(new Color(13f / 255f, 16f / 255f, 21f / 255f)));
                    EditorGUI.DrawRect(new Rect(barRect.x, barRect.y, barRect.width * 0.55f, barRect.height),
                        WPFMATheme.Shift(new Color(78f / 255f, 140f / 255f, 184f / 255f)));
                    GUI.Label(new Rect(right - 74f, row.y, 70f, row.height), "importing",
                        new GUIStyle(importerMetaStyle) { normal = { textColor = AccentBlue } });
                    continue;
                }

                DrawSafetyBadge(new Rect(badgeX, row.y + 4f, badgeWidth, row.height - 8f), entry.Path);

                GUI.Label(new Rect(sizeX, row.y, sizeWidth, row.height), FormatBytes(entry.Bytes),
                    new GUIStyle(importerMetaStyle) { alignment = TextAnchor.MiddleRight, normal = { textColor = wasImported ? DimText : MetaText } });

                if (showDate)
                    GUI.Label(new Rect(dateX, row.y, dateWidth, row.height),
                        wasImported ? "imported" : entry.Added.ToString("d MMM"),
                        new GUIStyle(importerMetaStyle) { alignment = TextAnchor.MiddleRight, normal = { textColor = wasImported ? FaintText : DimText } });

                var buttonRect = new Rect(right - buttonWidth, row.y + 3f, buttonWidth, 18f);
                if (GUI.Button(buttonRect, "Import", selected ? accentButtonStyle : importerOutlineButtonStyle))
                    ImportPackageNow(entry.Path);
            }

            HandleImporterDragAndDrop(listRect);
        }

        /// <summary>What the package check found for this package (checked in the background); click for the details.</summary>
        private void DrawSafetyBadge(Rect rect, string packagePath)
        {
            if (!WPFMASafety.ListBadges)
                return;
            var report = WPFMASafety.Cached(packagePath);
            string text = report == null ? "checking..." : report.Badge;
            Color color = report == null ? FaintText
                : report.Level == SafetyLevel.Danger ? new Color(230f / 255f, 107f / 255f, 115f / 255f)
                : report.Level == SafetyLevel.Check || report.Error != null ? new Color(239f / 255f, 159f / 255f, 39f / 255f)
                : new Color(93f / 255f, 202f / 255f, 165f / 255f);

            var style = new GUIStyle(importerMetaStyle) { alignment = TextAnchor.MiddleCenter, normal = { textColor = color } };
            if (report != null && report.Level >= SafetyLevel.Check)
            {
                EditorGUI.DrawRect(rect, new Color(color.r, color.g, color.b, 0.16f));
                style.fontStyle = FontStyle.Bold;
            }
            GUI.Label(rect, new GUIContent(text, "Package check: click to see what's inside"), style);

            if (report == null)
                return;
            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
            if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && rect.Contains(Event.current.mousePosition))
            {
                Event.current.Use();
                WPFMASafetyWindow.ShowPackage(report, choice => WPFMASafety.ImportChoice(report, packagePath, true, choice));
            }
        }

        private void HandleImporterDragAndDrop(Rect listRect)
        {
            var hintRect = GUILayoutUtility.GetRect(0f, 18f, GUILayout.ExpandWidth(true));
            var dropArea = new Rect(listRect.x, listRect.y, listRect.width, listRect.height + hintRect.height);
            bool hovering = dropArea.Contains(Event.current.mousePosition);
            bool dragging = DragAndDrop.paths != null && DragAndDrop.paths.Any(IsUnityPackage);

            EditorGUI.DrawRect(new Rect(hintRect.x, hintRect.y, hintRect.width, 1f), Separator);
            GUI.Label(new Rect(hintRect.x + 8f, hintRect.y, hintRect.width - 16f, hintRect.height),
                "drag .unitypackage files here to add them",
                new GUIStyle(importerPathStyle) { normal = { textColor = dragging && hovering ? AccentBlue : FaintText } });

            if (!hovering)
                return;

            if (Event.current.type == EventType.DragUpdated && dragging)
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                Event.current.Use();
            }
            else if (Event.current.type == EventType.DragPerform && dragging)
            {
                DragAndDrop.AcceptDrag();
                Directory.CreateDirectory(ImportFolderPath);

                foreach (var path in DragAndDrop.paths.Where(IsUnityPackage))
                {
                    string destination = Path.Combine(ImportFolderPath, Path.GetFileName(path));
                    if (Path.GetFullPath(destination) == Path.GetFullPath(path))
                        continue;

                    try
                    {
                        File.Copy(path, destination, true);
                    }
                    catch (Exception e)
                    {
                        Debug.LogWarning("[WPFMA-SDK] Could not copy '" + Path.GetFileName(path) + "': " + e.Message);
                    }
                }

                AssetDatabase.Refresh();
                Event.current.Use();
                Repaint();
            }
        }

        private static bool IsUnityPackage(string path)
        {
            return !string.IsNullOrEmpty(path) && path.EndsWith(".unitypackage", StringComparison.OrdinalIgnoreCase);
        }

        private void DrawImporterStatusBar(PackageEntry[] packages)
        {
            var rect = GUILayoutUtility.GetRect(0f, 28f, GUILayout.ExpandWidth(true));
            EditorGUI.DrawRect(rect, ToolbarBackground);
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), ToolbarEdge);

            int queued = WPFMAPackageImportQueue.Items.Count;
            string status;
            if (WPFMAPackageImportQueue.IsProcessing)
                status = "Queue: " + WPFMAPackageImportQueue.GetCurrentPackageName() +
                         (queued > 0 ? ", " + queued + " waiting" : string.Empty);
            else if (queued > 0)
                status = "Queue: " + queued + (queued == 1 ? " package waiting" : " packages waiting");
            else if (importerSelection.Count > 0)
                status = importerSelection.Count + " selected";
            else
                status = "Nothing queued";

            float clearWidth = ButtonWidth(importerToolbarButtonStyle, "Clear");
            float queueWidth = ButtonWidth(importerToolbarButtonStyle, "Queue selected");
            var clearRect = new Rect(rect.xMax - ScrollbarGutter - clearWidth - 4f, rect.y + 4f, clearWidth, 20f);
            var queueRect = new Rect(clearRect.x - queueWidth - 5f, rect.y + 4f, queueWidth, 20f);

            GUI.Label(new Rect(rect.x + 8f, rect.y, queueRect.x - rect.x - 12f, rect.height), status,
                new GUIStyle(importerRowNameStyle) { normal = { textColor = DimText } });

            if (GUI.Button(clearRect, "Clear", importerToolbarButtonStyle))
            {
                WPFMAPackageImportQueue.Clear();
                importerSelection.Clear();
                Repaint();
            }

            if (GUI.Button(queueRect, "Queue selected", importerToolbarButtonStyle))
            {
                var wanted = packages.Where(e => importerSelection.Contains(e.Path)).Select(e => e.Path).ToArray();
                if (wanted.Length > 0)
                {
                    WPFMAPackageImportQueue.EnqueueMany(wanted);
                    WPFMAPackageImportQueue.StartIfNeeded();
                }
            }
        }

        private void OpenImportFolder()
        {
            WPFMADiscordPresence.SetBusyState("Opening import folder", 10d);
            Directory.CreateDirectory(ImportFolderPath);

            EditorUtility.RevealInFinder(Path.GetFullPath(ImportFolderPath));
        }

        private void ExportImports()
        {
            string packagePath = EditorUtility.SaveFilePanel(
                "Export imported packages",
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                "WPFMA-SDK-Imports",
                "unitypackage");

            if (string.IsNullOrEmpty(packagePath))
                return;

            WPFMADiscordPresence.SetBusyState("Exporting imports", 10d);
            try
            {
                AssetDatabase.ExportPackage(ImportFolderPath, packagePath, ExportPackageOptions.Recurse);
                EditorUtility.RevealInFinder(packagePath);
            }
            finally
            {
                WPFMADiscordPresence.ClearBusyState();
            }
        }

        private static string FormatBytes(long bytes)
        {
            if (bytes >= 1048576L)
                return (bytes / 1048576f).ToString("0.0") + " MB";
            if (bytes >= 1024L)
                return (bytes / 1024f).ToString("0") + " KB";
            return bytes + " B";
        }

        private static float ButtonWidth(GUIStyle style, string label, float padding = 16f)
        {
            return Mathf.Ceil(style.CalcSize(new GUIContent(label)).x) + padding;
        }

        private const float ScrollbarGutter = 15f;

        private static string[] GetPackages()
        {
            Directory.CreateDirectory(ImportFolderPath);
            return Directory.GetFiles(ImportFolderPath, "*.unitypackage", SearchOption.TopDirectoryOnly);
        }

        private sealed class RipperTabState
        {
            private const string WindowTitle = "WPFMA-SDK Exporter";
            private const string DefaultOutputName = "WPFMA_Rips";
            private const string DefaultProjectFolder = "Assets/WPFMA-SDK/Rips~";

            private const string OutputPrefKey = "WPFMA.VrcaRipper.OutputRoot";
            private const string ScenePrefKey = "WPFMA.VrcaRipper.UsePreviewScene";
            private const string GroundPrefKey = "WPFMA.VrcaRipper.IncludeGround";
            private const string CopyPrefKey = "WPFMA.VrcaRipper.CopyIntoProject";
            private const string ProjectFolderPrefKey = "WPFMA.VrcaRipper.ProjectFolder";
            private const string SettingsPrefKey = "WPFMA.VrcaRipper.SettingsExpanded";
            private const string SessionFile = "ProjectSettings/WPFMA-SDK-Ripper.txt";

            private bool sessionLoaded;
            private const string ExportFolderPrefKey = "WPFMA.VrcaRipper.ExportFolder";
            private const string ExportShaderPrefKey = "WPFMA.VrcaRipper.ExportShader";
            private const string DefaultExportFolder = "Assets/WPFMA-SDK/Rips";

            private static Color PanelBackground => WPFMATheme.Shift(new Color(17f / 255f, 20f / 255f, 25f / 255f));
            private static Color DropBackground => WPFMATheme.Shift(new Color(33f / 255f, 38f / 255f, 46f / 255f));
            private static Color DropHighlight => WPFMATheme.Shift(new Color(40f / 255f, 66f / 255f, 88f / 255f));
            private static Color AccentBlue => WPFMATheme.Shift(new Color(126f / 255f, 182f / 255f, 222f / 255f));
            private static Color AccentText => WPFMATheme.Shift(new Color(14f / 255f, 24f / 255f, 33f / 255f));
            private static Color ToolbarBackground => WPFMATheme.Shift(new Color(24f / 255f, 29f / 255f, 37f / 255f));
            private static Color ToolbarEdge => WPFMATheme.Shift(new Color(11f / 255f, 14f / 255f, 18f / 255f));
            private static Color DropStripBackground => WPFMATheme.Shift(new Color(19f / 255f, 24f / 255f, 31f / 255f));
            private static Color RowOdd => WPFMATheme.Shift(new Color(21f / 255f, 26f / 255f, 33f / 255f));
            private static Color RowEven => WPFMATheme.Shift(new Color(18f / 255f, 22f / 255f, 28f / 255f));
            private static Color RowSelected => WPFMATheme.Shift(new Color(40f / 255f, 66f / 255f, 88f / 255f));
            private static Color DetailBackground => WPFMATheme.Shift(new Color(15f / 255f, 19f / 255f, 24f / 255f));
            private static Color Separator => WPFMATheme.Shift(new Color(33f / 255f, 38f / 255f, 46f / 255f));
            private static Color MetaText => WPFMATheme.Shift(new Color(143f / 255f, 163f / 255f, 181f / 255f));
            private static Color DimText => WPFMATheme.Shift(new Color(110f / 255f, 124f / 255f, 139f / 255f));
            private static Color FaintText => WPFMATheme.Shift(new Color(78f / 255f, 91f / 255f, 105f / 255f));
            private static readonly Color OkGreen = new Color(93f / 255f, 202f / 255f, 165f / 255f);
            private static readonly Color WarnAmber = new Color(239f / 255f, 159f / 255f, 39f / 255f);
            private static readonly Color ErrorRed = new Color(226f / 255f, 75f / 255f, 74f / 255f);

            private sealed class Entry
            {
                public string Path;
                public string Header;
                public string Error;
                public bool Encrypted;
                public List<WPFMAVrcaNode> Nodes;
                public bool Expanded;
                public string Status;
                public bool Exported;
                public bool Failed;
                public bool IsScene;
                public System.Threading.Tasks.Task<WPFMABundleShaders.BundleScan> ShaderScan;
                public List<WPFMABundleShaders.Found> ShaderNames;
                public List<WPFMABundleSystems.Found> Systems;
                public bool SystemsExpanded;
                public string ShaderError;
                public List<WPFMABundleShaders.Need> Shaders;
                public int BuiltInShaders;
                public int ShadersCheckedAt = -1;
                public bool ShadersExpanded = true;

                public bool Usable => Error == null && !Encrypted;
            }

            private readonly List<Entry> entries = new List<Entry>();
            private WPFMAWindow owner;
            private string outputRoot;
            private string projectFolder;
            private bool usePreviewScene;
            private bool includeGround;
            private bool copyIntoProject;
            private bool settingsExpanded;
            private string exportFolder;
            private Shader exportShader;
            private Vector2 scrollPosition;
            [NonSerialized] private GUIStyle accentButtonStyle;
            [NonSerialized] private GUIStyle toolbarButtonStyle;
            [NonSerialized] private GUIStyle rowNameStyle;
            [NonSerialized] private GUIStyle metaStyle;
            [NonSerialized] private GUIStyle outlineButtonStyle;

            public void DrawPanel(WPFMAWindow owner)
            {
                this.owner = owner;
                EnsureVisualStyles();
                // The background starts where the panel does, so it doesn't paint over what's above it (the Exporter's
                // warning box sat under it as an empty gap).
                var top = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
                if (Event.current.type == EventType.Repaint)
                    EditorGUI.DrawRect(new Rect(0f, top.y, owner.position.width, owner.position.height), PanelBackground);

                LoadSettingsOnce();
                LoadSession();

                DrawRipperToolbar();
                DrawDropStrip();
                DrawRipperOptions();

                using (var scroll = new EditorGUILayout.ScrollViewScope(scrollPosition))
                {
                    scrollPosition = scroll.scrollPosition;
                    DrawRipperRows();
                }

                DrawRipperStatusBar();
            }

            private int stylesTheme = -1;

            private void EnsureVisualStyles()
            {
                if (stylesTheme != WPFMATheme.Version)
                {
                    stylesTheme = WPFMATheme.Version;
                    accentButtonStyle = null;
                }
                if (accentButtonStyle != null && accentButtonStyle.normal.background != null &&
                    toolbarButtonStyle != null && rowNameStyle != null && metaStyle != null && outlineButtonStyle != null)
                    return;

                var texture = new Texture2D(1, 1);
                texture.SetPixel(0, 0, AccentBlue);
                texture.Apply();
                texture.hideFlags = HideFlags.HideAndDontSave;

                accentButtonStyle = new GUIStyle(GUI.skin.button)
                {
                    normal = { background = texture, textColor = AccentText },
                    hover = { background = texture, textColor = AccentText },
                    active = { background = texture, textColor = AccentText },
                    focused = { background = texture, textColor = AccentText },
                    fontSize = 12
                };

                toolbarButtonStyle = CreateFlatButtonStyle(WPFMATheme.Shift(new Color(31f / 255f, 37f / 255f, 46f / 255f)), WPFMATheme.Shift(new Color(0.79f, 0.83f, 0.87f)));
                toolbarButtonStyle.fontSize = 12;
                toolbarButtonStyle.padding = new RectOffset(7, 7, 2, 2);
                outlineButtonStyle = CreateFlatButtonStyle(WPFMATheme.Shift(new Color(31f / 255f, 37f / 255f, 46f / 255f)), WPFMATheme.Shift(new Color(0.79f, 0.83f, 0.87f)));
                outlineButtonStyle.fontSize = 12;
                rowNameStyle = new GUIStyle(EditorStyles.label)
                {
                    fontSize = 12,
                    normal = { textColor = WPFMATheme.Shift(new Color(0.79f, 0.83f, 0.87f)) },
                    alignment = TextAnchor.MiddleLeft
                };
                metaStyle = new GUIStyle(EditorStyles.label)
                {
                    fontSize = 11,
                    normal = { textColor = WPFMATheme.Shift(new Color(143f / 255f, 163f / 255f, 181f / 255f)) },
                    alignment = TextAnchor.MiddleRight
                };
            }

            private void LoadSettingsOnce()
            {
                if (!string.IsNullOrEmpty(outputRoot))
                    return;

                outputRoot = EditorPrefs.GetString(OutputPrefKey, string.Empty);
                if (string.IsNullOrEmpty(outputRoot))
                    outputRoot = Path.Combine(ProjectRoot, DefaultOutputName);

                projectFolder = EditorPrefs.GetString(ProjectFolderPrefKey, DefaultProjectFolder);
                usePreviewScene = EditorPrefs.GetBool(ScenePrefKey, false);
                includeGround = EditorPrefs.GetBool(GroundPrefKey, true);
                copyIntoProject = EditorPrefs.GetBool(CopyPrefKey, false);
                settingsExpanded = EditorPrefs.GetBool(SettingsPrefKey, false);
                exportFolder = EditorPrefs.GetString(ExportFolderPrefKey, DefaultExportFolder);

                string shaderName = EditorPrefs.GetString(ExportShaderPrefKey, string.Empty);
                exportShader = string.IsNullOrEmpty(shaderName) ? null : Shader.Find(shaderName);
            }

            private void DrawRipperToolbar()
            {
                var rect = GUILayoutUtility.GetRect(0f, 28f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(rect, ToolbarBackground);
                EditorGUI.DrawRect(new Rect(rect.x, rect.yMax - 1f, rect.width, 1f), ToolbarEdge);

                float top = rect.y + 4f;
                const float height = 20f;
                float x = rect.x + 6f;

                float width = ButtonWidth(toolbarButtonStyle, "Add .vrca");
                if (GUI.Button(new Rect(x, top, width, height), "Add .vrca", toolbarButtonStyle))
                {
                    string picked = EditorUtility.OpenFilePanel("Select a bundle (.vrca, .vrcw, .vrcb)", string.Empty,
                        WPFMABundleFiles.PickerFilter);
                    if (!string.IsNullOrEmpty(picked))
                        AddPath(picked);
                }

                x += width + 5f;
                width = ButtonWidth(toolbarButtonStyle, "Add folder");
                if (GUI.Button(new Rect(x, top, width, height), "Add folder", toolbarButtonStyle))
                {
                    string picked = EditorUtility.OpenFolderPanel("Select a folder of .vrca bundles", string.Empty, string.Empty);
                    if (!string.IsNullOrEmpty(picked))
                        AddPath(picked);
                }

                x += width + 5f;
                width = ButtonWidth(toolbarButtonStyle, "Clear");
                using (new EditorGUI.DisabledScope(entries.Count == 0))
                {
                    if (GUI.Button(new Rect(x, top, width, height), "Clear", toolbarButtonStyle))
                    {
                        entries.Clear();
                        SaveSession();
                    }
                }

                x += width + 5f;
                width = ButtonWidth(toolbarButtonStyle, "Extract files");
                using (new EditorGUI.DisabledScope(entries.Count == 0))
                {
                    if (GUI.Button(new Rect(x, top, width, height),
                            new GUIContent("Extract files", "Unpack the raw files inside the bundle to the folder on the right."),
                            toolbarButtonStyle))
                        ExtractEntries(entries);
                }

                x += width + 8f;
                var revealRect = new Rect(rect.xMax - ScrollbarGutter - 26f, top, 24f, height);
                if (GUI.Button(revealRect, "\u2197", toolbarButtonStyle))
                    RevealOutputRoot();

                float folderWidth = Mathf.Min(160f, revealRect.x - x - 74f);
                var folderRect = new Rect(revealRect.x - folderWidth - 4f, top, folderWidth, height);
                if (folderWidth >= 60f)
                {
                    GUI.Label(new Rect(folderRect.x - 66f, rect.y, 62f, rect.height), "extracts to",
                        new GUIStyle(metaStyle) { normal = { textColor = FaintText } });

                    if (GUI.Button(folderRect, new GUIContent(CompactPath(outputRoot), outputRoot), toolbarButtonStyle))
                    {
                        string picked = EditorUtility.OpenFolderPanel("Choose an output folder", outputRoot, string.Empty);
                        if (!string.IsNullOrEmpty(picked))
                        {
                            outputRoot = picked;
                            EditorPrefs.SetString(OutputPrefKey, outputRoot);
                        }
                    }
                }
            }

            private void DrawDropStrip()
            {
                var rect = GUILayoutUtility.GetRect(0f, 30f, GUILayout.ExpandWidth(true));
                var evt = Event.current;
                bool canAccept = CanAcceptDrag();
                bool hovering = rect.Contains(evt.mousePosition);
                bool active = hovering && canAccept;

                // An accent-outlined drop zone with bright text, so it stands out from the rows around it.
                EditorGUI.DrawRect(rect, active ? DropHighlight : DropStripBackground);
                var edge = active ? Color.white : AccentBlue;
                EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), edge);
                EditorGUI.DrawRect(new Rect(rect.x, rect.yMax - 1f, rect.width, 1f), edge);
                EditorGUI.DrawRect(new Rect(rect.x, rect.y, 1f, rect.height), edge);
                EditorGUI.DrawRect(new Rect(rect.xMax - 1f, rect.y, 1f, rect.height), edge);
                GUI.Label(rect, active ? "Drop to add" : "Drag .vrca files or a folder here",
                    new GUIStyle(rowNameStyle)
                    {
                        alignment = TextAnchor.MiddleCenter,
                        fontSize = 12,
                        fontStyle = FontStyle.Bold,
                        normal = { textColor = active ? Color.white : AccentBlue }
                    });

                if (!hovering)
                    return;

                if (evt.type == EventType.DragUpdated && canAccept)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    evt.Use();
                    owner.Repaint();
                }
                else if (evt.type == EventType.DragPerform && canAccept)
                {
                    DragAndDrop.AcceptDrag();
                    foreach (var path in DragAndDrop.paths)
                        AddPath(path);
                    foreach (var obj in DragAndDrop.objectReferences)
                    {
                        var assetPath = AssetDatabase.GetAssetPath(obj);
                        if (!string.IsNullOrEmpty(assetPath))
                            AddPath(assetPath);
                    }

                    evt.Use();
                    owner.Repaint();
                }
            }

            private void DrawRipperOptions()
            {
                var rect = GUILayoutUtility.GetRect(0f, 26f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(new Rect(rect.x, rect.yMax - 1f, rect.width, 1f), Separator);

                float x = rect.x + 6f;
                x = DrawInlineToggle(rect, x, "preview scene", usePreviewScene, value =>
                {
                    usePreviewScene = value;
                    EditorPrefs.SetBool(ScenePrefKey, value);
                });

                using (new EditorGUI.DisabledScope(!usePreviewScene))
                {
                    x = DrawInlineToggle(rect, x, "ground", includeGround, value =>
                    {
                        includeGround = value;
                        EditorPrefs.SetBool(GroundPrefKey, value);
                    });
                }

                x = DrawInlineToggle(rect, x, "copy into project", copyIntoProject, value =>
                {
                    copyIntoProject = value;
                    EditorPrefs.SetBool(CopyPrefKey, value);
                });

                bool clearBlueprint = EditorPrefs.GetBool(WPFMAVrcaExporter.ClearBlueprintPrefKey, true);
                x = DrawInlineToggle(rect, x, "clear blueprint", clearBlueprint,
                    value => EditorPrefs.SetBool(WPFMAVrcaExporter.ClearBlueprintPrefKey, value));

                float rightEdge = rect.xMax - ScrollbarGutter - 4f;

                float renameWidth = Mathf.Min(140f, rightEdge - x - 66f);
                if (renameWidth < 50f)
                    return;

                var renameRect = new Rect(rightEdge - renameWidth - 6f, rect.y + 3f, renameWidth, 20f);
                GUI.Label(new Rect(renameRect.x - 62f, rect.y, 58f, rect.height), "rename to",
                    new GUIStyle(metaStyle) { normal = { textColor = FaintText } });

                string rename = EditorPrefs.GetString(WPFMAVrcaExporter.RenamePrefKey, string.Empty);
                string edited = EditorGUI.TextField(renameRect, rename);
                if (edited != rename)
                    EditorPrefs.SetString(WPFMAVrcaExporter.RenamePrefKey, edited);
            }

            private float DrawInlineToggle(Rect row, float x, string label, bool value, Action<bool> onChange)
            {
                float width = GUI.skin.label.CalcSize(new GUIContent(label)).x + 22f;
                bool edited = GUI.Toggle(new Rect(x, row.y + 5f, width, 17f), value, label,
                    new GUIStyle(EditorStyles.toggle) { fontSize = 11 });
                if (edited != value)
                    onChange(edited);

                return x + width + 8f;
            }

            private const int RipperPageSize = 10;

            private int ripperPage;

            private void DrawRipperRows()
            {
                if (entries.Count == 0)
                {
                    var empty = GUILayoutUtility.GetRect(0f, 21f, GUILayout.ExpandWidth(true));
                    GUI.Label(new Rect(empty.x + 8f, empty.y, empty.width, empty.height), "No bundles added yet.",
                        new GUIStyle(rowNameStyle) { normal = { textColor = DimText } });
                    return;
                }

                string previewed = WPFMAVrcaPreview.HasPreview ? WPFMAVrcaPreview.GetFirstLoadedPath() : null;

                int pageCount = Mathf.Max(1, Mathf.CeilToInt(entries.Count / (float)RipperPageSize));
                ripperPage = Mathf.Clamp(ripperPage, 0, pageCount - 1);

                int start = ripperPage * RipperPageSize;
                int end = Mathf.Min(entries.Count, start + RipperPageSize);

                for (int i = start; i < end; i++)
                {
                    var entry = entries[i];
                    var row = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
                    bool isPreviewed = previewed != null && SamePath(previewed, entry.Path);
                    EditorGUI.DrawRect(row, isPreviewed ? RowSelected : (i % 2 == 0 ? RowOdd : RowEven));

                    var chevron = new Rect(row.x + 5f, row.y, 16f, row.height);
                    if (GUI.Button(chevron, entry.Expanded ? "\u25BE" : "\u25B8", EditorStyles.label))
                        entry.Expanded = !entry.Expanded;

                    float right = row.xMax - ScrollbarGutter - 4f;
                    float removeWidth = 22f;
                    float previewWidth = ButtonWidth(outlineButtonStyle, "Preview");
                    float exportWidth = ButtonWidth(outlineButtonStyle, "Export");

                    var removeRect = new Rect(right - removeWidth, row.y + 3f, removeWidth, 18f);
                    if (GUI.Button(removeRect, "\u00D7", outlineButtonStyle))
                    {
                        entries.RemoveAt(i);
                        i--;
                        SaveSession();

                        end = Mathf.Min(entries.Count, start + RipperPageSize);
                        continue;
                    }

                    using (new EditorGUI.DisabledScope(!entry.Usable))
                    {
                        string previewLabel = entry.IsScene ? "Play scene" : "Preview";
                        previewWidth = ButtonWidth(outlineButtonStyle, previewLabel);

                        var previewRect = new Rect(removeRect.x - previewWidth - 4f, row.y + 3f, previewWidth, 18f);
                        if (GUI.Button(previewRect, new GUIContent(previewLabel, entry.IsScene
                                ? "Enters play mode and loads the world from the bundle. Nothing is written to the project."
                                : "Spawns the avatar in the scene."),
                                isPreviewed ? accentButtonStyle : outlineButtonStyle))
                        {
                            if (entry.IsScene)
                                WPFMAScenePreview.Request(entry.Path, null);
                            else
                                PreviewEntry(entry);
                        }

                        bool worldReady = entry.IsScene && FindWorldRoots(entry).Count > 0;
                        using (new EditorGUI.DisabledScope(entry.IsScene && !worldReady))
                        {
                            var exportRect = new Rect(previewRect.x - exportWidth - 4f, row.y + 3f, exportWidth, 18f);
                            if (GUI.Button(exportRect, new GUIContent("Export", entry.IsScene
                                    ? (worldReady
                                        ? "Rebuild the loaded world as meshes, materials, textures and prefabs."
                                        : "Press Play scene first, then export while the world is loaded.")
                                    : "Rebuild the avatar as project assets."), outlineButtonStyle))
                            {
                                if (entry.IsScene)
                                    ExportWorldEntry(entry);
                                else
                                    ExportEntry(entry);
                            }

                            right = exportRect.x - 6f;
                        }
                    }

                    string state;
                    Color stateColor;
                    if (entry.Error != null) { state = "unreadable"; stateColor = ErrorRed; }
                    else if (entry.Encrypted) { state = "encrypted"; stateColor = WarnAmber; }
                    else if (entry.Failed) { state = "failed"; stateColor = ErrorRed; }
                    else if (entry.IsScene) { state = "world"; stateColor = AccentBlue; }
                    else if (entry.Exported) { state = "exported"; stateColor = OkGreen; }
                    else if (isPreviewed) { state = "previewed"; stateColor = AccentBlue; }
                    else { state = "ready"; stateColor = DimText; }

                    GUI.Label(new Rect(right - 80f, row.y, 76f, row.height), state,
                        new GUIStyle(metaStyle) { normal = { textColor = stateColor } });

                    var info = new FileInfo(entry.Path);
                    GUI.Label(new Rect(right - 156f, row.y, 72f, row.height), info.Exists ? FormatSize(info.Length) : "missing",
                        new GUIStyle(metaStyle) { normal = { textColor = DimText } });

                    var nameRect = new Rect(row.x + 25f, row.y, Mathf.Max(60f, right - row.x - 186f), row.height);
                    GUI.Label(nameRect, new GUIContent(Path.GetFileName(entry.Path), entry.Path), rowNameStyle);

                    if (entry.Expanded)
                        DrawEntryDetail(entry);
                }

                DrawRipperPager(pageCount, start, end);
            }

            private void DrawNeededShaders(Entry entry)
            {
                bool layout = Event.current.type == EventType.Layout;

                if (layout && entry.ShaderScan == null && entry.ShaderNames == null && entry.ShaderError == null)
                {
                    string path = entry.Path;
                    entry.ShaderScan = System.Threading.Tasks.Task.Run(() => WPFMABundleShaders.ReadNames(path));
                }

                if (layout && entry.ShaderScan != null && entry.ShaderScan.IsCompleted)
                {
                    if (entry.ShaderScan.IsFaulted)
                    {
                        var problem = entry.ShaderScan.Exception != null
                            ? entry.ShaderScan.Exception.GetBaseException()
                            : null;
                        entry.ShaderError = problem != null ? problem.Message : "unknown error";
                    }
                    else
                    {
                        entry.ShaderNames = entry.ShaderScan.Result.Shaders;
                        entry.Systems = entry.ShaderScan.Result.Systems;
                    }

                    entry.ShaderScan = null;
                }

                if (layout && entry.ShaderNames != null && entry.ShadersCheckedAt != WPFMABundleShaders.ProjectVersion)
                {
                    int builtIn;
                    entry.Shaders = WPFMABundleShaders.Classify(entry.ShaderNames, out builtIn);
                    entry.BuiltInShaders = builtIn;
                    entry.ShadersCheckedAt = WPFMABundleShaders.ProjectVersion;
                }

                var head = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(head, DetailBackground);
                var headLabel = new Rect(head.x + 30f, head.y + 2f, head.width - 40f, 16f);
                var headStyle = new GUIStyle(rowNameStyle) { fontSize = 11, fontStyle = FontStyle.Bold };

                if (entry.ShaderScan != null || (entry.ShaderNames != null && entry.Shaders == null))
                {
                    headStyle.normal.textColor = DimText;
                    GUI.Label(headLabel, "Shaders needed: reading the bundle...", headStyle);
                    if (owner != null)
                        owner.Repaint();
                    return;
                }

                if (entry.ShaderError != null)
                {
                    headStyle.normal.textColor = WarnAmber;
                    GUI.Label(headLabel, new GUIContent("Shaders needed: could not read them", entry.ShaderError), headStyle);
                    return;
                }

                if (entry.Shaders == null)
                    return;

                int missing = entry.Shaders.Count(s => s.State == WPFMABundleShaders.State.Missing);
                int close = entry.Shaders.Count(s => s.State == WPFMABundleShaders.State.CloseMatch);

                string summary;
                if (entry.Shaders.Count == 0)
                {
                    summary = entry.BuiltInShaders > 0
                        ? "Shaders needed: only Unity/VRChat built-ins, nothing to install"
                        : "Shaders needed: none packed in this bundle";
                    headStyle.normal.textColor = OkGreen;
                }
                else
                {
                    summary = "Shaders needed: " + entry.Shaders.Count +
                              (missing > 0 ? "  |  " + missing + " missing" : "  |  all found") +
                              (close > 0 ? ", " + close + " close match" : string.Empty) +
                              (entry.BuiltInShaders > 0 ? "  |  +" + entry.BuiltInShaders + " built-in" : string.Empty);
                    headStyle.normal.textColor = missing > 0 ? ErrorRed : close > 0 ? AccentBlue : OkGreen;
                }

                if (entry.Shaders.Count == 0)
                {
                    GUI.Label(headLabel, summary, headStyle);
                    return;
                }

                GUI.Label(headLabel, (entry.ShadersExpanded ? "\u25BE " : "\u25B8 ") + summary, headStyle);
                if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && head.Contains(Event.current.mousePosition))
                {
                    entry.ShadersExpanded = !entry.ShadersExpanded;
                    Event.current.Use();
                }

                if (!entry.ShadersExpanded)
                    return;

                foreach (var shader in entry.Shaders)
                {
                    var line = GUILayoutUtility.GetRect(0f, 16f, GUILayout.ExpandWidth(true));
                    EditorGUI.DrawRect(line, DetailBackground);

                    string state;
                    Color color;
                    switch (shader.State)
                    {
                        case WPFMABundleShaders.State.Installed:
                            state = shader.VersionDiffers ? "installed, but you have v" + shader.HaveVersion : "installed";
                            color = shader.VersionDiffers ? WarnAmber : OkGreen;
                            break;
                        case WPFMABundleShaders.State.CloseMatch:
                            state = "will use " + shader.Match +
                                    (string.IsNullOrEmpty(shader.HaveVersion) ? string.Empty : " v" + shader.HaveVersion);
                            color = AccentBlue;
                            break;
                        default:
                            state = "missing";
                            color = ErrorRed;
                            break;
                    }

                    float stateWidth = Mathf.Min(260f, line.width * 0.45f);
                    string label = shader.Family +
                                   (string.IsNullOrEmpty(shader.Version) ? string.Empty : "  v" + shader.Version) +
                                   (shader.Variants > 1 ? "  x" + shader.Variants : string.Empty);
                    string tip = shader.FirstName == shader.Family
                        ? shader.FirstName
                        : shader.FirstName + "\n(locked or renamed copy of " + shader.Family + ")";

                    GUI.Label(new Rect(line.x + 42f, line.y, line.width - stateWidth - 60f, line.height),
                        new GUIContent(label, tip),
                        new GUIStyle(rowNameStyle) { fontSize = 11, normal = { textColor = MetaText } });
                    GUI.Label(new Rect(line.xMax - ScrollbarGutter - stateWidth - 6f, line.y, stateWidth, line.height),
                        new GUIContent(state, state),
                        new GUIStyle(metaStyle) { alignment = TextAnchor.MiddleRight, normal = { textColor = color } });
                }

                if (missing > 0)
                {
                    var hint = GUILayoutUtility.GetRect(0f, 16f, GUILayout.ExpandWidth(true));
                    EditorGUI.DrawRect(hint, DetailBackground);
                    GUI.Label(new Rect(hint.x + 42f, hint.y, hint.width - 60f, hint.height),
                        "Import the missing ones before exporting so the materials keep their look.",
                        new GUIStyle(metaStyle) { alignment = TextAnchor.MiddleLeft, normal = { textColor = DimText } });
                }
            }

            /// <summary>Under the shaders: the avatar systems it was built with (VRCFury, Modular Avatar and so on).</summary>
            private void DrawBuiltWith(Entry entry)
            {
                if (entry.Systems == null)
                    return;

                var head = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(head, DetailBackground);
                var headLabel = new Rect(head.x + 30f, head.y + 2f, head.width - 40f, 16f);
                var headStyle = new GUIStyle(rowNameStyle) { fontSize = 11, fontStyle = FontStyle.Bold };

                if (entry.Systems.Count == 0)
                {
                    headStyle.normal.textColor = DimText;
                    GUI.Label(headLabel, "Built with: no VRCFury, Modular Avatar or other systems found", headStyle);
                    return;
                }

                headStyle.normal.textColor = AccentBlue;
                string summary = "Built with: " + string.Join(", ", entry.Systems.Select(s => s.Name));
                GUI.Label(headLabel, new GUIContent((entry.SystemsExpanded ? "\u25BE " : "\u25B8 ") + summary, summary), headStyle);
                if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && head.Contains(Event.current.mousePosition))
                {
                    entry.SystemsExpanded = !entry.SystemsExpanded;
                    Event.current.Use();
                }

                if (!entry.SystemsExpanded)
                    return;

                foreach (var system in entry.Systems)
                {
                    var line = GUILayoutUtility.GetRect(0f, 16f, GUILayout.ExpandWidth(true));
                    EditorGUI.DrawRect(line, DetailBackground);
                    float nameWidth = Mathf.Min(220f, line.width * 0.4f);
                    GUI.Label(new Rect(line.x + 42f, line.y, nameWidth, line.height), system.Name,
                        new GUIStyle(rowNameStyle) { fontSize = 11, normal = { textColor = MetaText } });
                    GUI.Label(new Rect(line.x + 42f + nameWidth, line.y, line.width - nameWidth - 60f - ScrollbarGutter, line.height),
                        new GUIContent(system.Evidence, system.Evidence),
                        new GUIStyle(metaStyle) { alignment = TextAnchor.MiddleRight, normal = { textColor = DimText } });
                }

                foreach (var note in new[] { WPFMABundleSystems.BakedNote, WPFMABundleSystems.StackWarning })
                {
                    var hint = GUILayoutUtility.GetRect(0f, 16f, GUILayout.ExpandWidth(true));
                    EditorGUI.DrawRect(hint, DetailBackground);
                    GUI.Label(new Rect(hint.x + 42f, hint.y, hint.width - 60f, hint.height), new GUIContent(note, note),
                        new GUIStyle(metaStyle) { alignment = TextAnchor.MiddleLeft, normal = { textColor = note == WPFMABundleSystems.StackWarning ? WarnAmber : DimText } });
                }
            }

            private void DrawRipperPager(int pageCount, int start, int end)
            {
                if (entries.Count == 0)
                    return;

                if (pageCount <= 1)
                {
                    var single = GUILayoutUtility.GetRect(0f, 18f, GUILayout.ExpandWidth(true));
                    GUI.Label(new Rect(single.xMax - ScrollbarGutter - 200f, single.y, 196f, single.height),
                        entries.Count + (entries.Count == 1 ? " bundle" : " bundles") +
                        (entries.Count < RipperPageSize ? string.Empty : ", 1 page"),
                        new GUIStyle(metaStyle) { normal = { textColor = DimText } });
                    return;
                }

                var bar = GUILayoutUtility.GetRect(0f, 24f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(bar, ToolbarBackground);
                EditorGUI.DrawRect(new Rect(bar.x, bar.y, bar.width, 1f), ToolbarEdge);

                float buttonWidth = 28f;
                float x = bar.x + 6f;

                using (new EditorGUI.DisabledScope(ripperPage <= 0))
                {
                    if (GUI.Button(new Rect(x, bar.y + 3f, buttonWidth, 18f), "\u25C0", outlineButtonStyle))
                    {
                        ripperPage--;
                        GUI.changed = true;
                    }
                }

                x += buttonWidth + 4f;

                using (new EditorGUI.DisabledScope(ripperPage >= pageCount - 1))
                {
                    if (GUI.Button(new Rect(x, bar.y + 3f, buttonWidth, 18f), "\u25B6", outlineButtonStyle))
                    {
                        ripperPage++;
                        GUI.changed = true;
                    }
                }

                x += buttonWidth + 10f;

                GUI.Label(new Rect(x, bar.y, 200f, bar.height),
                    "Page " + (ripperPage + 1) + " of " + pageCount,
                    new GUIStyle(rowNameStyle) { normal = { textColor = DimText } });

                int shown = Mathf.Max(0, end - start);
                GUI.Label(new Rect(bar.xMax - ScrollbarGutter - 156f, bar.y, 152f, bar.height),
                    shown == 0 ? entries.Count + " total" : (start + 1) + "-" + (start + shown) + " of " + entries.Count,
                    new GUIStyle(metaStyle) { normal = { textColor = DimText } });
            }

            private void DrawEntryDetail(Entry entry)
            {
                if (entry.Error != null)
                {
                    EditorGUILayout.HelpBox(entry.Error, MessageType.Error);
                    return;
                }

                if (entry.Encrypted)
                {
                    EditorGUILayout.HelpBox(entry.Header + "\n\nThis bundle is encrypted, so its contents cannot be read.",
                        MessageType.Warning);
                    return;
                }

                var header = GUILayoutUtility.GetRect(0f, 17f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(new Rect(header.x, header.y, header.width, header.height), DetailBackground);
                GUI.Label(new Rect(header.x + 30f, header.y, header.width - 40f, header.height), entry.Header,
                    new GUIStyle(rowNameStyle) { fontSize = 11, normal = { textColor = DimText } });

                if (entry.IsScene)
                {
                    foreach (var scene in WPFMAScenePreview.SceneNames(entry.Nodes))
                    {
                        var sceneRow = GUILayoutUtility.GetRect(0f, 16f, GUILayout.ExpandWidth(true));
                        EditorGUI.DrawRect(sceneRow, DetailBackground);
                        GUI.Label(new Rect(sceneRow.x + 30f, sceneRow.y, sceneRow.width - 40f, sceneRow.height),
                            "scene: " + scene,
                            new GUIStyle(rowNameStyle) { fontSize = 11, normal = { textColor = AccentBlue } });
                    }
                }

                if (entry.Nodes != null)
                {
                    foreach (var node in entry.Nodes)
                    {
                        var line = GUILayoutUtility.GetRect(0f, 16f, GUILayout.ExpandWidth(true));
                        EditorGUI.DrawRect(line, DetailBackground);
                        GUI.Label(new Rect(line.x + 30f, line.y, line.width - 110f, line.height), node.Path,
                            new GUIStyle(rowNameStyle) { fontSize = 11, normal = { textColor = MetaText } });
                        GUI.Label(new Rect(line.xMax - ScrollbarGutter - 76f, line.y, 70f, line.height), FormatSize(node.Size),
                            new GUIStyle(metaStyle) { normal = { textColor = DimText } });
                    }
                }

                DrawNeededShaders(entry);
                DrawBuiltWith(entry);

                if (entry.Status == null)
                    return;

                var status = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(status, DetailBackground);
                GUI.Label(new Rect(status.x + 30f, status.y, status.width - 120f, status.height), entry.Status,
                    new GUIStyle(rowNameStyle)
                    {
                        fontSize = 11,
                        normal = { textColor = entry.Failed ? ErrorRed : (entry.Exported ? OkGreen : MetaText) }
                    });

                string report = FindReport(entry);
                if (report == null)
                    return;

                float reportWidth = ButtonWidth(outlineButtonStyle, "Open report");
                if (GUI.Button(new Rect(status.xMax - ScrollbarGutter - reportWidth - 4f, status.y, reportWidth, 18f),
                        "Open report", outlineButtonStyle))
                    EditorUtility.OpenWithDefaultApp(report);
            }

            private string FindReport(Entry entry)
            {
                try
                {
                    string folder = (string.IsNullOrEmpty(exportFolder) ? DefaultExportFolder : exportFolder).TrimEnd('/', '\\') +
                                    "/" + WPFMAVrcaExporter.RipFolderName(entry.Path);
                    string report = Path.Combine(folder, "export report.txt");
                    return File.Exists(report) ? report : null;
                }
                catch (Exception)
                {
                    return null;
                }
            }

            private void DrawRipperStatusBar()
            {
                var rect = GUILayoutUtility.GetRect(0f, 28f, GUILayout.ExpandWidth(true));
                EditorGUI.DrawRect(rect, ToolbarBackground);
                EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), ToolbarEdge);

                bool hasPreview = WPFMAVrcaPreview.HasPreview;
                var avatar = hasPreview ? WPFMAVrcaPreview.GetPreviewedAvatar() : null;
                string status = !hasPreview
                    ? "Nothing previewed"
                    : "In scene: " + (avatar != null ? avatar.name : Path.GetFileName(WPFMAVrcaPreview.GetFirstLoadedPath() ?? "preview"));

                float clearWidth = ButtonWidth(toolbarButtonStyle, "Clear");
                float exportWidth = ButtonWidth(accentButtonStyle, "Export preview", 20f);
                var clearRect = new Rect(rect.xMax - ScrollbarGutter - clearWidth - 4f, rect.y + 4f, clearWidth, 20f);
                var exportRect = new Rect(clearRect.x - exportWidth - 5f, rect.y + 4f, exportWidth, 20f);

                GUI.Label(new Rect(rect.x + 8f, rect.y, (hasPreview ? exportRect.x : rect.xMax) - rect.x - 12f, rect.height),
                    status, new GUIStyle(rowNameStyle) { normal = { textColor = hasPreview ? MetaText : DimText } });

                if (!hasPreview)
                    return;

                if (GUI.Button(clearRect, "Clear", toolbarButtonStyle))
                    WPFMAVrcaPreview.Clear();

                if (GUI.Button(exportRect, "Export preview", accentButtonStyle))
                    ExportPreview();
            }

            private static bool SamePath(string left, string right)
            {
                try
                {
                    return string.Equals(Path.GetFullPath(left), Path.GetFullPath(right), StringComparison.OrdinalIgnoreCase);
                }
                catch (Exception)
                {
                    return string.Equals(left, right, StringComparison.OrdinalIgnoreCase);
                }
            }

            private static string CompactPath(string path)
            {
                if (string.IsNullOrEmpty(path))
                    return "(not set)";

                string name = Path.GetFileName(path.TrimEnd('/', '\\'));
                return string.IsNullOrEmpty(name) ? path : name;
            }

            private static bool CanAcceptDrag()
            {
                foreach (var path in DragAndDrop.paths)
                {
                    if (string.IsNullOrEmpty(path))
                        continue;

                    if (Directory.Exists(path))
                        return true;

                    if (WPFMABundleFiles.IsBundle(path))
                        return true;
                }

                foreach (var obj in DragAndDrop.objectReferences)
                {
                    var assetPath = AssetDatabase.GetAssetPath(obj);
                    if (!string.IsNullOrEmpty(assetPath) && WPFMABundleFiles.IsBundle(assetPath))
                        return true;
                }

                return false;
            }

            internal void DrawSettingsSection(WPFMAWindow owner)
            {
                this.owner = owner;
                EnsureVisualStyles();
                DrawSettings();
            }

            private void DrawSettings()
            {
                if (string.IsNullOrEmpty(outputRoot))
                {
                    outputRoot = EditorPrefs.GetString(OutputPrefKey, string.Empty);
                    if (string.IsNullOrEmpty(outputRoot))
                        outputRoot = Path.Combine(ProjectRoot, DefaultOutputName);

                    projectFolder = EditorPrefs.GetString(ProjectFolderPrefKey, DefaultProjectFolder);
                    usePreviewScene = EditorPrefs.GetBool(ScenePrefKey, false);
                    includeGround = EditorPrefs.GetBool(GroundPrefKey, true);
                    copyIntoProject = EditorPrefs.GetBool(CopyPrefKey, false);
                    settingsExpanded = EditorPrefs.GetBool(SettingsPrefKey, false);
                    exportFolder = EditorPrefs.GetString(ExportFolderPrefKey, DefaultExportFolder);

                    string shaderName = EditorPrefs.GetString(ExportShaderPrefKey, string.Empty);
                    exportShader = string.IsNullOrEmpty(shaderName) ? null : Shader.Find(shaderName);
                }

                EditorGUILayout.Space(6f);
                EditorGUI.indentLevel++;

                EditorGUILayout.LabelField("Extract to", EditorStyles.boldLabel);
                using (new EditorGUILayout.HorizontalScope())
                {
                    string edited = EditorGUILayout.TextField(outputRoot);
                    if (edited != outputRoot)
                    {
                        outputRoot = edited;
                        EditorPrefs.SetString(OutputPrefKey, outputRoot);
                    }

                    if (DrawActionButton("Browse", 20f, GUILayout.Width(80f)))
                    {
                        string picked = EditorUtility.OpenFolderPanel("Choose an output folder", outputRoot, string.Empty);
                        if (!string.IsNullOrEmpty(picked))
                        {
                            outputRoot = picked;
                            EditorPrefs.SetString(OutputPrefKey, outputRoot);
                            GUI.FocusControl(null);
                        }
                    }
                }

                if (IsInsideAssets(outputRoot) && !IsHiddenFromImporter(outputRoot))
                {
                    EditorGUILayout.HelpBox(
                        "That folder is inside Assets, so Unity will try to import every extracted file. On large bundles that can stall the editor.",
                        MessageType.Warning);
                }

                EditorGUILayout.Space(8f);
                EditorGUILayout.LabelField("Unity project handoff", EditorStyles.boldLabel);

                using (new EditorGUI.DisabledScope(!copyIntoProject))
                {
                    string editedFolder = EditorGUILayout.TextField("Project folder", projectFolder);
                    if (editedFolder != projectFolder)
                    {
                        projectFolder = editedFolder;
                        EditorPrefs.SetString(ProjectFolderPrefKey, projectFolder);
                    }
                }

                if (copyIntoProject)
                {
                    EditorGUILayout.HelpBox(
                        IsHiddenFromImporter(projectFolder)
                            ? "The trailing ~ keeps this folder inside the project but hidden from Unity's importer, so the copied files travel with the project without being imported. Remove it and Unity will import every file."
                            : "Unity will import everything copied here. Ending the folder name with ~ keeps the files in the project but skips importing them.",
                        IsHiddenFromImporter(projectFolder) ? MessageType.Info : MessageType.Warning);
                }

                EditorGUILayout.Space(10f);
                EditorGUILayout.LabelField("Avatar identity", EditorStyles.boldLabel);

                string rename = EditorPrefs.GetString(WPFMAVrcaExporter.RenamePrefKey, string.Empty);
                string editedRename = EditorGUILayout.TextField("Rename to", rename);
                if (editedRename != rename)
                    EditorPrefs.SetString(WPFMAVrcaExporter.RenamePrefKey, editedRename);

                EditorGUILayout.LabelField(
                    string.IsNullOrEmpty(editedRename.Trim())
                        ? "Empty keeps the name from the bundle."
                        : "Root object and prefab file both become '" + editedRename.Trim() + "'.",
                    EditorStyles.miniLabel);

                EditorGUILayout.Space(4f);

                bool editedClear = EditorPrefs.GetBool(WPFMAVrcaExporter.ClearBlueprintPrefKey, true);
                EditorGUILayout.HelpBox(
                    editedClear
                        ? "The exported prefab carries no blueprint ID, so uploading creates a new avatar. This is what " +
                          "you want when recovering onto an account that does not own the original record."
                        : "The blueprint ID is kept, so uploading tries to update that existing avatar. That only works " +
                          "on the account which owns it.",
                    MessageType.None);

                EditorGUILayout.Space(4f);
                if (DrawActionButton("Build preview scene now", 24f))
                {
                    WPFMADiscordPresence.SetBusyState("Building preview scene");
                    try
                    {
                        WPFMAVrcaPreview.CreatePreviewScene(includeGround);
                    }
                    finally
                    {
                        WPFMADiscordPresence.ClearBusyState();
                    }
                }

                EditorGUILayout.Space(10f);
                EditorGUILayout.LabelField("While exporting", EditorStyles.boldLabel);

                var expiry = WPFMAArchive.ExpiresAt;
                bool expired = expiry > DateTime.MinValue && expiry < DateTime.UtcNow;
                bool unlocked = WPFMAArchive.IsUnlocked && !expired;

                using (new EditorGUILayout.HorizontalScope())
                {
                    var lockStyle = new GUIStyle(EditorStyles.miniLabel)
                    {
                        fontStyle = FontStyle.Bold,
                        normal = { textColor = unlocked ? OkGreen : WarnAmber }
                    };

                    EditorGUILayout.LabelField(
                        unlocked ? "Archive: unlocked" : expired ? "Archive: expired" : "Archive: locked", lockStyle,
                        GUILayout.Width(120f));

                    if (!unlocked && GUILayout.Button("Redeem a code", EditorStyles.miniButton, GUILayout.Width(110f)))
                        owner.GoToSettings();
                }

                using (new EditorGUI.DisabledScope(!unlocked))
                {
                    bool fetchShaders = unlocked && EditorPrefs.GetBool(WPFMAVrcaExporter.FetchShadersPrefKey, true);
                    bool editedFetch = EditorGUILayout.ToggleLeft("Download missing shaders from the archive", fetchShaders);
                    if (unlocked && editedFetch != fetchShaders)
                        EditorPrefs.SetBool(WPFMAVrcaExporter.FetchShadersPrefKey, editedFetch);
                }

                EditorGUILayout.LabelField(
                    unlocked
                        ? (string.IsNullOrEmpty(WPFMAArchive.Label)
                            ? "Off skips the lookup and matches against what is already installed."
                            : WPFMAArchive.Label + ". Off skips the lookup and matches what is installed.")
                        : expired
                            ? "That access code expired. Redeem a new one to pull missing shaders."
                            : "Redeem an access code to pull missing shaders while exporting.",
                    EditorStyles.miniLabel);

                bool writeReport = EditorPrefs.GetBool(WPFMAVrcaExporter.WriteReportPrefKey, true);
                bool editedReport = EditorGUILayout.ToggleLeft("Write an export report", writeReport);
                if (editedReport != writeReport)
                    EditorPrefs.SetBool(WPFMAVrcaExporter.WriteReportPrefKey, editedReport);

                EditorGUILayout.LabelField(
                    "Saves 'export report.txt' beside the export: what came out, and what could not be recovered.",
                    EditorStyles.miniLabel);

                bool forceWeight = EditorPrefs.GetBool(WPFMAVrcaExporter.ForceLayerWeightPrefKey, false);
                bool editedForce = EditorGUILayout.ToggleLeft("Force every layer weight to 1", forceWeight);
                if (editedForce != forceWeight)
                    EditorPrefs.SetBool(WPFMAVrcaExporter.ForceLayerWeightPrefKey, editedForce);

                EditorGUILayout.LabelField(
                    "Off by default: the export restores the weights the avatar shipped with, and a layer left at 0 " +
                    "is often driven by an Animator Layer Control. Turn on if you keep getting silent layers.",
                    EditorStyles.miniLabel);

                bool verbose = EditorPrefs.GetBool(WPFMAVrcaExporter.VerboseLogPrefKey, true);
                bool editedVerbose = EditorGUILayout.ToggleLeft("Log each step to the console", verbose);
                if (editedVerbose != verbose)
                    EditorPrefs.SetBool(WPFMAVrcaExporter.VerboseLogPrefKey, editedVerbose);

                EditorGUILayout.LabelField(
                    "Off leaves only the start and finish lines, plus any warnings.",
                    EditorStyles.miniLabel);

                EditorGUILayout.Space(10f);
                EditorGUILayout.LabelField("Export to project assets", EditorStyles.boldLabel);

                string editedExport = EditorGUILayout.TextField("Export folder", exportFolder);
                if (editedExport != exportFolder)
                {
                    exportFolder = editedExport;
                    EditorPrefs.SetString(ExportFolderPrefKey, exportFolder);
                }

                var editedShader = (Shader)EditorGUILayout.ObjectField("Target shader", exportShader, typeof(Shader), false);
                if (editedShader != exportShader)
                {
                    exportShader = editedShader;
                    EditorPrefs.SetString(ExportShaderPrefKey, exportShader != null ? exportShader.name : string.Empty);
                }

                EditorGUILayout.HelpBox(
                    (exportShader == null
                        ? "Leave the shader empty and each material is matched to the installed shader sharing the most property names. "
                        : "Every material will be rebuilt on '" + exportShader.name + "'. ") +
                    "Shaders themselves cannot be recovered — a bundle stores compiled GPU programs and a project shader is source, " +
                    "so materials are rebuilt on a real shader and the recovered textures rebound by name.",
                    MessageType.Info);

                EditorGUI.indentLevel--;
            }

            private void RevealOutputRoot()
            {
                if (string.IsNullOrEmpty(outputRoot))
                    return;

                Directory.CreateDirectory(outputRoot);
                EditorUtility.RevealInFinder(outputRoot);
            }

            private void PreviewEntry(Entry entry)
            {
                if (!WPFMAVrcaPreview.EnsureBuildTarget())
                    return;

                if (usePreviewScene && !WPFMAVrcaPreview.HasPreview)
                    WPFMAVrcaPreview.CreatePreviewScene(includeGround);

                string message;
                try
                {
                    WPFMADiscordPresence.SetBusyState("Previewing: " + Path.GetFileNameWithoutExtension(entry.Path));
                    EditorUtility.DisplayProgressBar(WindowTitle, "Loading " + Path.GetFileName(entry.Path) + "…", 0.5f);
                    var instance = WPFMAVrcaPreview.Preview(entry.Path, out message);
                    entry.Status = instance != null ? "Preview: " + message : "Preview failed: " + message;
                    entry.Failed = instance == null;
                    if (entry.Failed)
                        entry.Expanded = true;

                    if (instance == null)
                        Debug.LogWarning("[WPFMA-SDK] Could not preview " + entry.Path + ": " + message);
                }
                catch (Exception e)
                {
                    entry.Status = "Preview failed: " + e.Message;
                    entry.Failed = true;
                    Debug.LogError("[WPFMA-SDK] Could not preview " + entry.Path + ": " + e);
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                    WPFMADiscordPresence.ClearBusyState();
                    if (SceneView.lastActiveSceneView != null)
                        SceneView.lastActiveSceneView.Repaint();
                    if (owner != null)
                        owner.Repaint();
                }
            }

            private bool ConfirmExportFolder(string projectRelativeFolder)
            {
                string full = Path.Combine(ProjectRoot, projectRelativeFolder);
                if (!Directory.Exists(full) || Directory.GetFileSystemEntries(full).Length == 0)
                    return true;

                bool replace = EditorUtility.DisplayDialog(WindowTitle,
                    projectRelativeFolder + " already contains an export.\n\n" +
                    "Exporting again would add a second copy of every asset alongside the old one, and it is easy to end up " +
                    "inspecting the stale prefab.\n\nReplace the existing export? The old one goes to the Recycle Bin.",
                    "Replace", "Cancel");

                if (!replace)
                    return false;

                if (!AssetDatabase.MoveAssetToTrash(projectRelativeFolder))
                    AssetDatabase.DeleteAsset(projectRelativeFolder);
                AssetDatabase.Refresh();
                return true;
            }

            private static List<GameObject> FindWorldRoots(Entry entry)
            {
                var roots = new List<GameObject>();
                if (!EditorApplication.isPlaying || entry == null || !entry.IsScene)
                    return roots;

                var names = WPFMAScenePreview.SceneNames(entry.Nodes);
                for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCount; i++)
                {
                    var scene = UnityEngine.SceneManagement.SceneManager.GetSceneAt(i);
                    if (!scene.isLoaded || !names.Contains(scene.name))
                        continue;

                    foreach (var root in scene.GetRootGameObjects())
                    {
                        if (root != null)
                            roots.Add(root);
                    }
                }

                return roots;
            }

            private void ExportWorldEntry(Entry entry)
            {
                var roots = FindWorldRoots(entry);
                if (roots.Count == 0)
                {
                    EditorUtility.DisplayDialog(WindowTitle,
                        "Load the world first with Play scene, then export while it is open.", "OK");
                    return;
                }

                string folder = (string.IsNullOrEmpty(exportFolder) ? DefaultExportFolder : exportFolder).TrimEnd('/', '\\') +
                                "/" + WPFMAVrcaExporter.RipFolderName(entry.Path);

                if (!ConfirmExportFolder(folder))
                    return;

                if (!EditorUtility.DisplayDialog(WindowTitle,
                        "Rebuild " + roots.Count + " root object(s) from this world?" + "\n\n" +
                        "Meshes, materials and textures come back. Udon programs, baked lighting and the scene's own " +
                        "settings do not - they live in the scene file, not on the objects.",
                        "Export", "Cancel"))
                    return;

                try
                {
                    WPFMADiscordPresence.SetBusyState("Exporting world: " + Path.GetFileNameWithoutExtension(entry.Path));
                    var report = WPFMAVrcaExporter.ExportWorld(entry.Path, roots, folder, exportShader,
                        (fraction, status) => !EditorUtility.DisplayCancelableProgressBar(WindowTitle,
                            Path.GetFileName(entry.Path) + "  \u2014  " + status, fraction));

                    entry.Status = "Exported world: " + report.Summary + " to " + folder;
                    entry.Exported = true;
                    entry.Failed = false;
                    entry.Expanded = true;
                    LogReport(Path.GetFileName(entry.Path), report);
                }
                catch (Exception e)
                {
                    entry.Status = "World export failed: " + e.Message;
                    entry.Failed = true;
                    Debug.LogError("[WPFMA-SDK] Could not export world " + entry.Path + ": " + e);
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                    WPFMADiscordPresence.ClearBusyState();
                    if (owner != null)
                        owner.Repaint();
                }
            }

            private void ExportEntry(Entry entry)
            {
                if (!WPFMAVrcaPreview.EnsureBuildTarget())
                    return;

                string folder = (string.IsNullOrEmpty(exportFolder) ? DefaultExportFolder : exportFolder).TrimEnd('/', '\\') +
                                "/" + WPFMAVrcaExporter.RipFolderName(entry.Path);

                if (!ConfirmExportFolder(folder))
                    return;

                try
                {
                    WPFMADiscordPresence.SetBusyState("Exporting: " + Path.GetFileNameWithoutExtension(entry.Path));
                    var report = WPFMAVrcaExporter.Export(entry.Path, folder, exportShader, (fraction, status) =>
                        !EditorUtility.DisplayCancelableProgressBar(WindowTitle, Path.GetFileName(entry.Path) + "  —  " + status, fraction));

                    entry.Status = "Exported " + report.Summary + " to " + folder;
                    entry.Exported = true;
                    entry.Failed = false;
                    LogReport(Path.GetFileName(entry.Path), report);

                    if (!string.IsNullOrEmpty(report.PrefabPath))
                    {
                        var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(report.PrefabPath);
                        if (prefab != null)
                        {
                            Selection.activeObject = prefab;
                            EditorGUIUtility.PingObject(prefab);
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    entry.Status = "Export cancelled.";
                }
                catch (Exception e)
                {
                    entry.Status = "Export failed: " + e.Message;
                    entry.Failed = true;
                    Debug.LogError("[WPFMA-SDK] Could not export " + entry.Path + ": " + e);
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                    WPFMADiscordPresence.ClearBusyState();
                    if (owner != null)
                        owner.Repaint();
                }
            }

            private void ExportPreview()
            {
                var avatar = WPFMAVrcaPreview.GetPreviewedAvatar();
                if (avatar == null)
                {
                    EditorUtility.DisplayDialog(WindowTitle, "Preview an avatar first, then export it.", "OK");
                    return;
                }

                string intactReason;
                if (!WPFMAVrcaExporter.IsPreviewIntact(avatar, out intactReason))
                {
                    EditorUtility.DisplayDialog(WindowTitle, intactReason, "OK");
                    return;
                }

                string folder = (string.IsNullOrEmpty(exportFolder) ? DefaultExportFolder : exportFolder).TrimEnd('/', '\\') +
                                "/" + avatar.name;

                if (!ConfirmExportFolder(folder))
                    return;

                try
                {
                    WPFMADiscordPresence.SetBusyState("Exporting preview: " + avatar.name);
                    var report = WPFMAVrcaExporter.ExportFromInstance(avatar, folder, exportShader, (fraction, status) =>
                        !EditorUtility.DisplayCancelableProgressBar(WindowTitle, avatar.name + "  —  " + status, fraction),
                        WPFMAVrcaPreview.GetFirstLoadedPath());

                    LogReport(avatar.name + " (from preview)", report);

                    if (!string.IsNullOrEmpty(report.PrefabPath))
                    {
                        var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(report.PrefabPath);
                        if (prefab != null)
                        {
                            Selection.activeObject = prefab;
                            EditorGUIUtility.PingObject(prefab);
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    Debug.LogWarning("[WPFMA-SDK] Preview export cancelled.");
                }
                catch (Exception e)
                {
                    Debug.LogError("[WPFMA-SDK] Could not export the preview: " + e);
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                    WPFMADiscordPresence.ClearBusyState();
                }
            }

            private static void LogReport(string label, WPFMAVrcaExporter.Report report)
            {
                var vrchat = report.VrchatComponents.OrderByDescending(c => c.Value).ToList();

                string components = vrchat.Count > 0
                    ? "\nVRChat components kept: " + string.Join(", ", vrchat.Select(c => c.Key + " x" + c.Value))
                    : "\nNo VRChat components resolved — check that the VRChat SDK is installed.";

                Debug.Log("[WPFMA-SDK] Exported " + label + ": " + report.Summary + components +
                          (report.MissingScriptsStripped > 0
                              ? "\nDropped " + report.MissingScriptsStripped + " component(s) with unresolvable scripts."
                              : string.Empty));

                if (report.Warnings.Count == 0)
                    return;

                const int shown = 25;
                var text = new System.Text.StringBuilder("[WPFMA-SDK] " + label + ": " +
                                                         report.Warnings.Count + " warning(s)");
                for (int i = 0; i < report.Warnings.Count && i < shown; i++)
                    text.Append("\n  - ").Append(report.Warnings[i]);

                if (report.Warnings.Count > shown)
                    text.Append("\n  ...and ").Append(report.Warnings.Count - shown)
                        .Append(" more, all of them in the export report.");

                Debug.LogWarning(text.ToString());
            }

            private void ExtractEntries(List<Entry> targets)
            {
                if (string.IsNullOrEmpty(outputRoot))
                {
                    EditorUtility.DisplayDialog(WindowTitle, "Choose an output folder first.", "OK");
                    return;
                }

                EditorPrefs.SetString(OutputPrefKey, outputRoot);

                foreach (var entry in targets)
                {
                    if (string.IsNullOrEmpty(entry.Status) || !entry.Status.StartsWith("Preview:", StringComparison.Ordinal))
                    {
                        entry.Status = "Preview required before extraction.";
                        Debug.LogWarning("[WPFMA-SDK] Extraction blocked for " + entry.Path + ": preview required before extraction.");
                        return;
                    }
                }

                int succeeded = 0;
                int failed = 0;
                bool copied = false;
                WPFMADiscordPresence.SetBusyState("Exporting " + targets.Count + " bundle(s)");

                try
                {
                    foreach (var entry in targets)
                    {
                        if (!entry.Usable)
                            continue;

                        string name = Path.GetFileNameWithoutExtension(entry.Path);
                        string destination = Path.Combine(outputRoot, name);

                        try
                        {
                            using (var stream = File.OpenRead(entry.Path))
                            {
                                var bundle = WPFMAVrcaBundle.Open(stream);
                                var written = bundle.Extract(stream, destination, (fraction, status) =>
                                    !EditorUtility.DisplayCancelableProgressBar(WindowTitle, name + "  —  " + status, fraction));

                                entry.Status = "Extracted " + written.Count + " file(s) to " + destination;
                                succeeded++;
                            }

                            if (copyIntoProject)
                            {
                                string target = CopyIntoProject(destination, name);
                                entry.Status += "  |  copied to " + target;
                                copied = true;
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            entry.Status = "Cancelled.";
                            Debug.LogWarning("[WPFMA-SDK] VRCA extraction cancelled: " + entry.Path);
                            return;
                        }
                        catch (Exception e)
                        {
                            entry.Status = "Failed: " + e.Message;
                            failed++;
                            Debug.LogError("[WPFMA-SDK] Could not extract " + entry.Path + ": " + e);
                        }
                    }
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                    WPFMADiscordPresence.ClearBusyState();
                    if (owner != null)
                        owner.Repaint();
                }

                if (copied && !IsHiddenFromImporter(projectFolder))
                    AssetDatabase.Refresh();

                Debug.Log("[WPFMA-SDK] Exporter finished: " + succeeded + " extracted, " + failed + " failed.");
            }

            private string CopyIntoProject(string sourceDirectory, string name)
            {
                string relative = string.IsNullOrEmpty(projectFolder) ? DefaultProjectFolder : projectFolder;
                string destination = Path.Combine(Path.Combine(ProjectRoot, relative), name);

                Directory.CreateDirectory(destination);

                foreach (var file in Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories))
                {
                    string tail = file.Substring(sourceDirectory.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    string copy = Path.Combine(destination, tail);
                    Directory.CreateDirectory(Path.GetDirectoryName(copy));
                    File.Copy(file, copy, true);
                }

                return relative + "/" + name;
            }

            private void AddPath(string path)
            {
                if (string.IsNullOrEmpty(path))
                    return;

                if (Directory.Exists(path))
                {
                    foreach (var file in WPFMABundleFiles.Find(path, SearchOption.AllDirectories))
                        AddFile(file);
                    return;
                }

                if (File.Exists(path))
                    AddFile(path);
            }

            private void AddFile(string path)
            {
                string full = Path.GetFullPath(path);
                foreach (var existing in entries)
                {
                    if (string.Equals(existing.Path, full, StringComparison.OrdinalIgnoreCase))
                        return;
                }

                entries.Add(Inspect(full));
                SaveSession();
            }

            private void LoadSession()
            {
                if (sessionLoaded)
                    return;

                sessionLoaded = true;

                try
                {
                    if (!File.Exists(SessionFile))
                        return;

                    foreach (var line in File.ReadAllLines(SessionFile))
                    {
                        var path = line.Trim();

                        if (path.Length == 0 || !File.Exists(path))
                            continue;

                        bool known = false;
                        foreach (var existing in entries)
                        {
                            if (string.Equals(existing.Path, path, StringComparison.OrdinalIgnoreCase))
                            {
                                known = true;
                                break;
                            }
                        }

                        if (!known)
                            entries.Add(Inspect(path));
                    }
                }
                catch (Exception e)
                {
                    Debug.LogWarning("[WPFMA-SDK] Could not restore the Exporter list: " + e.Message);
                }
            }

            private void SaveSession()
            {
                try
                {
                    if (entries.Count == 0)
                    {
                        if (File.Exists(SessionFile))
                            File.Delete(SessionFile);
                        return;
                    }

                    var paths = new List<string>(entries.Count);
                    foreach (var entry in entries)
                    {
                        if (!string.IsNullOrEmpty(entry.Path))
                            paths.Add(entry.Path);
                    }

                    Directory.CreateDirectory(Path.GetDirectoryName(SessionFile));
                    File.WriteAllLines(SessionFile, paths.ToArray());
                }
                catch (Exception e)
                {
                    Debug.LogWarning("[WPFMA-SDK] Could not save the Exporter list: " + e.Message);
                }
            }

            private static Entry Inspect(string path)
            {
                var entry = new Entry { Path = path };

                try
                {
                    using (var stream = File.OpenRead(path))
                    {
                        var bundle = WPFMAVrcaBundle.Open(stream);
                        entry.Encrypted = bundle.UsesContentEncryption;
                        entry.Nodes = bundle.Nodes;
                        entry.IsScene = WPFMAScenePreview.IsSceneBundle(bundle.Nodes);

                        entry.Header = entry.Encrypted
                            ? "UnityFS v" + bundle.FormatVersion + "  |  Unity " + bundle.UnityRevision + "  |  encrypted"
                            : "UnityFS v" + bundle.FormatVersion + "  |  Unity " + bundle.UnityRevision +
                              "  |  " + bundle.Blocks.Count + " blocks, " + bundle.Nodes.Count + " files" +
                              "  |  " + FormatSize(bundle.TotalUncompressedSize) + " unpacked";
                    }
                }
                catch (Exception e)
                {
                    entry.Error = e.Message;
                }

                return entry;
            }

            private static bool IsHiddenFromImporter(string path)
            {
                if (string.IsNullOrEmpty(path))
                    return false;

                foreach (var segment in path.Split('/', '\\'))
                {
                    if (segment.EndsWith("~", StringComparison.Ordinal) || segment.StartsWith(".", StringComparison.Ordinal))
                        return true;
                }

                return false;
            }

            private static bool IsInsideAssets(string path)
            {
                if (string.IsNullOrEmpty(path))
                    return false;

                try
                {
                    string assets = Path.GetFullPath(Application.dataPath);
                    string candidate = Path.GetFullPath(path);
                    return candidate.StartsWith(assets, StringComparison.OrdinalIgnoreCase);
                }
                catch (Exception)
                {
                    return false;
                }
            }

            private static string FormatSize(long bytes)
            {
                if (bytes < 1024L)
                    return bytes + " B";
                if (bytes < 1024L * 1024L)
                    return (bytes / 1024f).ToString("F1") + " KB";
                if (bytes < 1024L * 1024L * 1024L)
                    return (bytes / (1024f * 1024f)).ToString("F1") + " MB";
                return (bytes / (1024f * 1024f * 1024f)).ToString("F2") + " GB";
            }

            private bool DrawActionButton(string label, float height, params GUILayoutOption[] options)
            {
                var layoutOptions = new GUILayoutOption[options.Length + 1];
                layoutOptions[0] = GUILayout.Height(height);
                options.CopyTo(layoutOptions, 1);
                return GUILayout.Button(label, accentButtonStyle, layoutOptions);
            }

            private static string ProjectRoot => Directory.GetParent(Application.dataPath).FullName;
        }
    }
}
#endif
