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

namespace IStalk.Editor.Inspectors
{
    [CustomEditor(typeof(TrapData_SO))]
    public class TrapDataEditor : UnityEditor.Editor
    {
        private TrapData_SO _trap;
        private bool _showDesignerPanel = true;

        private void OnEnable()
        {
            _trap = (TrapData_SO)target;
        }

        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            EditorGUILayout.Space(15);
            _showDesignerPanel = EditorGUILayout.Foldout(_showDesignerPanel, "Designer Panel", true);
            if (!_showDesignerPanel) return;

            DrawBalancePreview();
            DrawEyeTypeContext();
            DrawQuickActions();
            DrawValidation();
        }

        private void DrawBalancePreview()
        {
            EditorGUILayout.LabelField("Balance Analysis", EditorStyles.boldLabel);

            float costPerSec = _trap.effectDuration > 0 ? _trap.dreadCost / _trap.effectDuration : 0;
            float area = Mathf.PI * _trap.effectRadius * _trap.effectRadius;

            EditorGUILayout.LabelField($"  Dread cost: {_trap.dreadCost}");
            EditorGUILayout.LabelField($"  Effect duration: {_trap.effectDuration:F1}s");
            EditorGUILayout.LabelField($"  Cost efficiency: {costPerSec:F1} dread/sec");
            EditorGUILayout.LabelField($"  Area coverage: {area:F1}m² (radius {_trap.effectRadius:F1}m)");
            EditorGUILayout.LabelField($"  Arm delay: {_trap.armDelay:F1}s (time before trap is active)");
            EditorGUILayout.LabelField($"  Max active per match: {_trap.maxActivePerMatch}");

            var rules = FindRules();
            if (rules != null)
            {
                EditorGUILayout.Space(3);
                EditorGUILayout.LabelField("Economy Context", EditorStyles.boldLabel);
                float regenTime = _trap.dreadCost / rules.dreadBaseRegenRate;
                EditorGUILayout.LabelField($"  Time to regen cost: {regenTime:F1}s (passive only)");
                EditorGUILayout.LabelField($"  % of full dread pool: ~{_trap.dreadCost}% (pool varies by type)");
            }
        }

        private void DrawEyeTypeContext()
        {
            var rules = FindRules();
            if (rules == null) return;

            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Per Eye Type Cost", EditorStyles.boldLabel);
            float trapperCost = Mathf.RoundToInt(_trap.dreadCost * rules.trapperDreadCostMultiplier);
            EditorGUILayout.LabelField($"  Default Eye: {_trap.dreadCost} dread");
            EditorGUILayout.LabelField($"  Trapper Eye: {trapperCost} dread (x{rules.trapperDreadCostMultiplier:F2})");
            EditorGUILayout.LabelField($"  Trapper max active bonus: +{rules.trapperMaxActiveBonus}");
        }

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

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Generate ID"))
            {
                Undo.RecordObject(_trap, "Generate Trap ID");
                _trap.trapId = _trap.name.Replace(" ", "_").ToLower();
                EditorUtility.SetDirty(_trap);
            }
            if (GUILayout.Button("Preset: Cheap/Small"))
            {
                Undo.RecordObject(_trap, "Preset Cheap");
                _trap.dreadCost = 10; _trap.effectRadius = 2f; _trap.effectDuration = 999f; _trap.armDelay = 0.5f;
                EditorUtility.SetDirty(_trap);
            }
            if (GUILayout.Button("Preset: Expensive/Large"))
            {
                Undo.RecordObject(_trap, "Preset Expensive");
                _trap.dreadCost = 30; _trap.effectRadius = 5f; _trap.effectDuration = 20f; _trap.armDelay = 1f;
                EditorUtility.SetDirty(_trap);
            }
            EditorGUILayout.EndHorizontal();
        }

        private void DrawValidation()
        {
            EditorGUILayout.Space(10);
            bool hasIssues = false;

            if (string.IsNullOrEmpty(_trap.trapId))
            { EditorGUILayout.HelpBox("Trap ID is empty. Click 'Generate ID'.", MessageType.Error); hasIssues = true; }
            if (_trap.placedPrefab == null)
            { EditorGUILayout.HelpBox("No placed prefab assigned (needed for spawning).", MessageType.Warning); hasIssues = true; }
            if (_trap.dreadCost <= 0)
            { EditorGUILayout.HelpBox("Dread cost is 0 — Eye can spam this for free!", MessageType.Error); hasIssues = true; }
            if (_trap.effectRadius <= 0)
            { EditorGUILayout.HelpBox("Effect radius is 0 — trap has no area.", MessageType.Warning); hasIssues = true; }

            if (!hasIssues)
                EditorGUILayout.HelpBox("All checks pass. Trap is ready.", MessageType.Info);
        }

        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]));
        }
    }

    [CustomEditor(typeof(ShrineItemData_SO))]
    public class ShrineItemDataEditor : UnityEditor.Editor
    {
        private ShrineItemData_SO _item;
        private bool _showDesignerPanel = true;

        private void OnEnable()
        {
            _item = (ShrineItemData_SO)target;
        }

        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            EditorGUILayout.Space(15);
            _showDesignerPanel = EditorGUILayout.Foldout(_showDesignerPanel, "Designer Panel", true);
            if (!_showDesignerPanel) return;

            DrawBalancePreview();
            DrawUsagePattern();
            DrawQuickActions();
            DrawValidation();
        }

        private void DrawBalancePreview()
        {
            EditorGUILayout.LabelField("Balance Analysis", EditorStyles.boldLabel);

            EditorGUILayout.LabelField($"  Loot cost: {_item.lootCost}");
            EditorGUILayout.LabelField($"  Net weight change: {(_item.weightDelta >= 0 ? "+" : "")}{_item.weightDelta:F1}kg");

            if (_item.effectDuration > 0)
            {
                float costPerSec = (float)_item.lootCost / _item.effectDuration;
                EditorGUILayout.LabelField($"  Cost per second: {costPerSec:F2} loot/sec");
                EditorGUILayout.LabelField($"  Effect duration: {_item.effectDuration:F1}s");
            }
            else
            {
                EditorGUILayout.LabelField($"  Instant effect (no duration)");
            }

            if (_item.cooldown > 0)
            {
                float uptime = _item.effectDuration / (_item.effectDuration + _item.cooldown);
                EditorGUILayout.LabelField($"  Cooldown: {_item.cooldown:F1}s");
                EditorGUILayout.LabelField($"  Uptime: {uptime:P0}");
            }

            EditorGUILayout.LabelField($"  Consumed on use: {(_item.isConsumedOnUse ? "YES (one-shot)" : "No (reusable)")}");
        }

        private void DrawUsagePattern()
        {
            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField("Usage Pattern", EditorStyles.boldLabel);

            string pattern = _item.itemType switch
            {
                ShrineItemType.SmokeBomb => "Area denial — blocks Eye LoS in zone",
                ShrineItemType.Mirror => "Stealth — runner invisible to Eye",
                ShrineItemType.Decoy => "Misdirection — fake blip on Eye's screen",
                ShrineItemType.OcularPaint => "Aggression — blinds Eye in area",
                ShrineItemType.WeightReducer => "Economy — shed weight instantly",
                ShrineItemType.GrapplingHook => "Mobility — reach high/far places",
                ShrineItemType.FlashOrb => "Aggression — blinds Eye (dodgeable with eyelids)",
                ShrineItemType.LinkedSprintTotem => "Co-op — speed buff when runners are close",
                ShrineItemType.SilenceShroud => "Stealth — suppresses noise for duration",
                ShrineItemType.VitalityLink => "Co-op — shared health/buff aura",
                _ => "Unknown effect"
            };
            EditorGUILayout.LabelField($"  {pattern}");

            var rules = FindRules();
            if (rules != null && _item.lootCost > 0)
            {
                float pctOfThreshold = (float)_item.lootCost / rules.extractionThreshold * 100f;
                EditorGUILayout.LabelField($"  Cost as % of extraction threshold: {pctOfThreshold:F0}%");
            }
        }

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

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Generate ID"))
            {
                Undo.RecordObject(_item, "Generate Shrine Item ID");
                _item.itemId = _item.name.Replace(" ", "_").ToLower();
                EditorUtility.SetDirty(_item);
            }
            if (GUILayout.Button("Make Consumable"))
            {
                Undo.RecordObject(_item, "Make Consumable");
                _item.isConsumedOnUse = true;
                _item.cooldown = 0;
                EditorUtility.SetDirty(_item);
            }
            if (GUILayout.Button("Make Reusable"))
            {
                Undo.RecordObject(_item, "Make Reusable");
                _item.isConsumedOnUse = false;
                if (_item.cooldown <= 0) _item.cooldown = 15f;
                EditorUtility.SetDirty(_item);
            }
            EditorGUILayout.EndHorizontal();
        }

        private void DrawValidation()
        {
            EditorGUILayout.Space(10);
            bool hasIssues = false;

            if (string.IsNullOrEmpty(_item.itemId))
            { EditorGUILayout.HelpBox("Item ID is empty. Click 'Generate ID'.", MessageType.Error); hasIssues = true; }
            if (_item.lootCost <= 0)
            { EditorGUILayout.HelpBox("Loot cost is 0 — item is free at shrine!", MessageType.Warning); hasIssues = true; }
            if (!_item.isConsumedOnUse && _item.cooldown <= 0)
            { EditorGUILayout.HelpBox("Reusable with no cooldown — runner can spam this!", MessageType.Error); hasIssues = true; }
            if (_item.isConsumedOnUse && _item.cooldown > 0)
            { EditorGUILayout.HelpBox("Consumed AND has cooldown — cooldown is pointless since item is destroyed.", MessageType.Warning); hasIssues = true; }

            if (!hasIssues)
                EditorGUILayout.HelpBox("All checks pass. Shrine item is ready.", MessageType.Info);
        }

        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
