// Copyright (c) 2026 EzAdmin. All rights reserved.
// Licensed under the EzAdmin Client License. See LICENSE-CLIENT.txt.

using System;
using System.Reflection;
using EzAdmin.Client;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace EzAdmin.EditorTools
{
    [InitializeOnLoad]
    internal static class EzAdminToolbar
    {
        private static bool _added;
        private static int _tries;

        static EzAdminToolbar()
        {
            EditorApplication.update -= TryAdd;
            EditorApplication.update += TryAdd;
        }

        private static void TryAdd()
        {
            if (_added) return;
            if (_tries++ > 600) { Stop(); return; }
            try
            {
                Type toolbarType = typeof(Editor).Assembly.GetType("UnityEditor.Toolbar");
                if (toolbarType == null) { Stop(); return; }
                var toolbars = Resources.FindObjectsOfTypeAll(toolbarType);
                if (toolbars.Length == 0) return;
                var root = RootOf(toolbarType, toolbars[0]);
                if (root == null) return;
                if (root.Q("EzAdminToolbarButton") != null) { Stop(); return; }

                var zone = root.Q("ToolbarZoneLeftAlign") ?? root.Q("ToolbarZoneRightAlign");
                if (zone == null) return;

                var host = new VisualElement { name = "EzAdminToolbarButton" };
                host.style.flexGrow = 0;
                host.style.flexShrink = 0;
                host.style.width = 34;
                host.style.height = Length.Percent(100);
                host.style.justifyContent = Justify.Center;
                host.style.alignItems = Align.Center;

                var button = new IMGUIContainer(Draw);
                button.style.flexGrow = 1;
                button.style.alignSelf = Align.Stretch;
                host.Add(button);

                if (zone.name == "ToolbarZoneRightAlign") zone.Insert(0, host);
                else zone.Add(host);
                Stop();
            }
            catch (Exception)
            {
                Stop();
            }
        }

        private static VisualElement RootOf(Type toolbarType, UnityEngine.Object toolbar)
        {
            var field = toolbarType.GetField("m_Root", BindingFlags.NonPublic | BindingFlags.Instance)
                        ?? toolbarType.GetField("m_Root", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
            if (field != null && field.GetValue(toolbar) is VisualElement fromField) return fromField;

            var prop = toolbarType.GetProperty("rootVisualElement", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (prop != null && prop.GetValue(toolbar) is VisualElement fromProp) return fromProp;

            return null;
        }

        private static void Stop()
        {
            _added = true;
            EditorApplication.update -= TryAdd;
        }

        private static void Draw()
        {
            var rect = GUILayoutUtility.GetRect(30, 24, GUILayout.ExpandHeight(true));
            if (GUI.Button(rect, new GUIContent("", "EzAdmin"), GUIStyle.none))
                EzAdminMenu.Show(rect);
            float s = Mathf.Min(18f, rect.height - 2f);
            var icon = new Rect(rect.x + (rect.width - s) / 2f, rect.y + (rect.height - s) / 2f, s, s);
            if (EzAdminBrand.Logo(64) != null) GUI.DrawTexture(icon, EzAdminBrand.Logo(64), ScaleMode.ScaleToFit);
        }
    }
}
