#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using IStalk.Data;
using IStalk.Runner;

namespace IStalk.Editor.Inspectors
{
    [CustomEditor(typeof(WearableData_SO))]
    public class WearableDataEditor : UnityEditor.Editor
    {
        private WearableData_SO _wearable;
        private bool _showBalancePreview = true;

        private void OnEnable()
        {
            _wearable = (WearableData_SO)target;
        }

        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            EditorGUILayout.Space(15);

            if (_wearable.icon != null)
            {
                EditorGUILayout.LabelField("Icon Preview", EditorStyles.boldLabel);
                Rect rect = GUILayoutUtility.GetRect(64, 64);
                EditorGUI.DrawPreviewTexture(rect, _wearable.icon.texture);
                EditorGUILayout.Space(5);
            }

            _showBalancePreview = EditorGUILayout.Foldout(_showBalancePreview, "Balance Preview", true);
            if (_showBalancePreview)
            {
                EditorGUI.indentLevel++;
                DrawBalancePreview();
                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space(10);
            DrawQuickActions();
            DrawValidation();
        }

        private void DrawBalancePreview()
        {
            var rules = FindRules();

            EditorGUILayout.LabelField("Ability Info", EditorStyles.boldLabel);
            EditorGUILayout.LabelField($"  Type: {_wearable.abilityType}");
            EditorGUILayout.LabelField($"  Mode: {(_wearable.isPassive ? "Passive (always active while worn)" : "Active (cooldown-based)")}");

            if (!_wearable.isPassive)
            {
                EditorGUILayout.LabelField($"  Cooldown: {_wearable.cooldown:F1}s");
                if (_wearable.cooldown > 0)
                {
                    float uptime = 1f / (1f + _wearable.cooldown);
                    EditorGUILayout.LabelField($"  Max activation rate: {60f / _wearable.cooldown:F1} uses/min");
                }
            }

            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Movement Granted", EditorStyles.boldLabel);
            string movementDesc = _wearable.abilityType switch
            {
                WearableAbilityType.Dash => "Ground dash burst (directional)",
                WearableAbilityType.WallRun => "Run along vertical walls while sprinting",
                WearableAbilityType.AirDash => "Mid-air directional dash",
                WearableAbilityType.Slide => "Sprint + Crouch to slide under gaps",
                WearableAbilityType.Vault => "Auto-vault waist-height obstacles",
                WearableAbilityType.Grapple => "Hook to GrappleAnchor points, swing",
                _ => "Unknown"
            };
            EditorGUILayout.LabelField($"  {movementDesc}");

            if (rules != null)
            {
                float cd = _wearable.abilityType switch
                {
                    WearableAbilityType.Dash => rules.dashCooldown,
                    WearableAbilityType.AirDash => rules.airDashCooldown,
                    WearableAbilityType.Grapple => rules.grappleCooldown,
                    _ => 0
                };
                if (cd > 0)
                    EditorGUILayout.LabelField($"  GlobalRules cooldown: {cd:F1}s");
            }

            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Economy", EditorStyles.boldLabel);
            if (_wearable.lootCost > 0)
                EditorGUILayout.LabelField($"  Shrine cost: {_wearable.lootCost} loot");
            else
                EditorGUILayout.LabelField($"  Not purchasable (world drop only)");
            EditorGUILayout.LabelField($"  Throw range: {_wearable.throwRange:F1}m");

            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Slot Impact", EditorStyles.boldLabel);
            EditorGUILayout.LabelField($"  Occupies 1 of {(rules != null ? rules.maxWearableSlots : 2)} wearable slots");
            EditorGUILayout.LabelField($"  Weight: 0 (wearables are weightless)");
        }

        private void DrawQuickActions()
        {
            EditorGUILayout.LabelField("Quick Actions", EditorStyles.boldLabel);

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Generate ID from Name"))
            {
                Undo.RecordObject(_wearable, "Generate Wearable ID");
                _wearable.wearableId = _wearable.name.Replace(" ", "_").ToLower();
                EditorUtility.SetDirty(_wearable);
            }

            if (GUILayout.Button("Set as Active Ability"))
            {
                Undo.RecordObject(_wearable, "Set Active Ability");
                _wearable.isPassive = false;
                if (_wearable.cooldown <= 0) _wearable.cooldown = 3f;
                EditorUtility.SetDirty(_wearable);
            }

            if (GUILayout.Button("Set as Passive Ability"))
            {
                Undo.RecordObject(_wearable, "Set Passive Ability");
                _wearable.isPassive = true;
                _wearable.cooldown = 0;
                EditorUtility.SetDirty(_wearable);
            }
            EditorGUILayout.EndHorizontal();
        }

        private void DrawValidation()
        {
            EditorGUILayout.Space(10);
            if (string.IsNullOrEmpty(_wearable.wearableId))
                EditorGUILayout.HelpBox("Wearable ID is empty. Click 'Generate ID from Name'.", MessageType.Error);
            if (string.IsNullOrEmpty(_wearable.displayName))
                EditorGUILayout.HelpBox("Display Name is empty.", MessageType.Warning);
            if (_wearable.worldPrefab == null)
                EditorGUILayout.HelpBox("No world prefab assigned (needed for drops).", MessageType.Warning);
            if (!_wearable.isPassive && _wearable.cooldown <= 0)
                EditorGUILayout.HelpBox("Active ability with 0 cooldown — intended?", MessageType.Warning);
            if (_wearable.lootCost <= 0 && _wearable.worldPrefab == null)
                EditorGUILayout.HelpBox("No purchase cost AND no world prefab. How will players get this?", MessageType.Error);
        }

        private GlobalRules_SO FindRules()
        {
            if (GlobalRules_SO.Instance != null) return GlobalRules_SO.Instance;
            string[] guids = AssetDatabase.FindAssets("t:GlobalRules_SO");
            if (guids.Length == 0) return null;
            return AssetDatabase.LoadAssetAtPath<GlobalRules_SO>(AssetDatabase.GUIDToAssetPath(guids[0]));
        }
    }
}
#endif
