using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using MusicBeePlugin.Clouseau.Introspection;
using NLog;

namespace MusicBeePlugin.Clouseau.UI
{
    /// <summary>
    /// Form for inspecting the MusicBee menu system.
    /// Shows hierarchical tree of menu items, their properties, and allows invoking menu items.
    /// </summary>
    public class MenuInspectorForm : Form
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        // Dark theme colors
        private static readonly Color DarkBackground = Color.FromArgb(30, 30, 30);
        private static readonly Color DarkPanel = Color.FromArgb(45, 45, 48);
        private static readonly Color DarkBorder = Color.FromArgb(67, 67, 70);
        private static readonly Color DarkText = Color.FromArgb(241, 241, 241);
        private static readonly Color DarkTextDim = Color.FromArgb(153, 153, 153);
        private static readonly Color DarkAccent = Color.FromArgb(0, 122, 204);
        private static readonly Color DarkHover = Color.FromArgb(62, 62, 64);
        private static readonly Color DarkSuccess = Color.FromArgb(100, 200, 100);
        private static readonly Color DarkWarning = Color.FromArgb(255, 200, 100);
        private static readonly Color DarkMenu = Color.FromArgb(255, 180, 100);

        // UI Controls
        private SplitContainer _mainSplit;
        private TreeView _menuTree;
        private ListView _propertyList;
        private TextBox _searchBox;
        private Label _statusLabel;
        private Button _refreshButton;
        private Button _invokeButton;
        private Button _captureContextButton;
        private ComboBox _menuSourceCombo;
        private Panel _detailPanel;
        private Label _detailLabel;
        private CheckBox _showAllItemsCheck;

        // Data
        private readonly MenuWalker _menuWalker;
        private readonly ReflectionExplorer _reflectionExplorer;
        private Form _targetForm;
        private List<MenuItemDetail> _allMenuItems;
        private MenuItemDetail _selectedMenuItem;
        private bool _isCapturingContextMenu;

        /// <summary>
        /// Creates a new MenuInspectorForm.
        /// </summary>
        public MenuInspectorForm() : this(null)
        {
        }

        /// <summary>
        /// Creates a new MenuInspectorForm with a specific target form.
        /// </summary>
        /// <param name="targetForm">The form to inspect (null to auto-detect MusicBee main form).</param>
        public MenuInspectorForm(Form targetForm)
        {
            _menuWalker = new MenuWalker();
            _reflectionExplorer = new ReflectionExplorer();
            _targetForm = targetForm;

            InitializeComponents();
            LoadMenuTree();
        }

        private void InitializeComponents()
        {
            // Form properties
            Text = "Menu Inspector";
            Size = new Size(1000, 700);
            MinimumSize = new Size(800, 500);
            StartPosition = FormStartPosition.CenterScreen;
            BackColor = DarkBackground;
            ForeColor = DarkText;
            SizeGripStyle = SizeGripStyle.Show;

            // Main split container (left: tree, right: details)
            _mainSplit = new SplitContainer
            {
                Dock = DockStyle.Fill,
                Orientation = Orientation.Vertical,
                SplitterWidth = 4,
                BackColor = DarkBackground
            };
            _mainSplit.Panel1.BackColor = DarkBackground;
            _mainSplit.Panel2.BackColor = DarkBackground;
            Shown += (s, e) => {
                try {
                    _mainSplit.SplitterDistance = 450;
                    _mainSplit.Panel1MinSize = 300;
                    _mainSplit.Panel2MinSize = 250;
                } catch { }
            };

            // Left panel - Menu tree
            var leftPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = DarkBackground
            };

            // Toolbar - two rows
            var toolbar = new Panel
            {
                Dock = DockStyle.Top,
                Height = 75,
                BackColor = DarkPanel
            };

            // Row 1: Refresh, Source combo
            _refreshButton = CreateButton("Refresh", 10, 8, 70);
            _refreshButton.Height = 30;
            _refreshButton.Click += (s, e) => LoadMenuTree();
            toolbar.Controls.Add(_refreshButton);

            var sourceLabel = new Label
            {
                Text = "Source:",
                Location = new Point(100, 14),
                AutoSize = true,
                ForeColor = DarkText
            };
            toolbar.Controls.Add(sourceLabel);

            _menuSourceCombo = new ComboBox
            {
                Location = new Point(185, 10),
                Width = 120,
                DropDownStyle = ComboBoxStyle.DropDownList,
                BackColor = DarkPanel,
                ForeColor = DarkText,
                FlatStyle = FlatStyle.Flat
            };
            _menuSourceCombo.Items.AddRange(new[] { "All Menus", "Main Menu", "Context Menus" });
            _menuSourceCombo.SelectedIndex = 0;
            _menuSourceCombo.SelectedIndexChanged += (s, e) => LoadMenuTree();
            toolbar.Controls.Add(_menuSourceCombo);

            // Row 2: Include Separators checkbox
            _showAllItemsCheck = new CheckBox
            {
                Text = "Include Separators",
                Location = new Point(10, 45),
                AutoSize = true,
                ForeColor = DarkText,
                Checked = false
            };
            _showAllItemsCheck.CheckedChanged += (s, e) => LoadMenuTree();
            toolbar.Controls.Add(_showAllItemsCheck);

            leftPanel.Controls.Add(toolbar);

            // Search box
            _searchBox = new TextBox
            {
                Dock = DockStyle.Top,
                BackColor = DarkPanel,
                ForeColor = DarkText,
                BorderStyle = BorderStyle.FixedSingle,
                Font = new Font("Segoe UI", 9F),
                Height = 24
            };
            _searchBox.TextChanged += OnSearchChanged;
            _searchBox.GotFocus += (s, e) => { if (_searchBox.Text == "Search menu items...") _searchBox.Text = ""; _searchBox.ForeColor = DarkText; };
            _searchBox.LostFocus += (s, e) => { if (string.IsNullOrEmpty(_searchBox.Text)) { _searchBox.Text = "Search menu items..."; _searchBox.ForeColor = DarkTextDim; } };
            _searchBox.Text = "Search menu items...";
            _searchBox.ForeColor = DarkTextDim;
            leftPanel.Controls.Add(_searchBox);

            // Tree view
            _menuTree = new TreeView
            {
                Dock = DockStyle.Fill,
                BackColor = DarkPanel,
                ForeColor = DarkText,
                BorderStyle = BorderStyle.None,
                Font = new Font("Consolas", 9F),
                ShowLines = true,
                ShowPlusMinus = true,
                ShowRootLines = true,
                FullRowSelect = true
            };
            _menuTree.AfterSelect += OnMenuItemSelected;
            _menuTree.NodeMouseDoubleClick += OnMenuItemDoubleClick;
            leftPanel.Controls.Add(_menuTree);

            _mainSplit.Panel1.Controls.Add(leftPanel);

            // Right panel - Properties
            var rightPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = DarkBackground
            };

            // WinForms Dock order: add Bottom first, then Fill, then Top last

            // Detail panel (Bottom - add first)
            _detailPanel = new Panel
            {
                Dock = DockStyle.Bottom,
                Height = 130,
                BackColor = DarkPanel
            };

            var detailTitleLabel = new Label
            {
                Text = "Handler Details",
                Location = new Point(10, 10),
                AutoSize = true,
                ForeColor = DarkText,
                Font = new Font("Segoe UI", 9F, FontStyle.Bold)
            };
            _detailPanel.Controls.Add(detailTitleLabel);

            _detailLabel = new Label
            {
                Location = new Point(10, 35),
                Size = new Size(380, 85),
                ForeColor = DarkTextDim,
                Font = new Font("Consolas", 9F),
                Text = "Select a menu item to view details"
            };
            _detailPanel.Controls.Add(_detailLabel);

            rightPanel.Controls.Add(_detailPanel);

            // Property list (Fill - add second)
            _propertyList = new ListView
            {
                Dock = DockStyle.Fill,
                View = View.Details,
                FullRowSelect = true,
                GridLines = true,
                BackColor = DarkPanel,
                ForeColor = DarkText,
                BorderStyle = BorderStyle.None,
                Font = new Font("Consolas", 9F)
            };
            _propertyList.Columns.Add("Property", 120);
            _propertyList.Columns.Add("Value", 280);

            rightPanel.Controls.Add(_propertyList);

            // Properties toolbar (Top - add last so it appears at top)
            var propsToolbar = new Panel
            {
                Dock = DockStyle.Top,
                Height = 55,
                BackColor = DarkPanel
            };

            _invokeButton = CreateButton("Click", 10, 10, 80);
            _invokeButton.Height = 30;
            _invokeButton.BackColor = Color.FromArgb(80, 130, 180);
            _invokeButton.Click += OnInvokeMenuItem;
            _invokeButton.Enabled = false;
            propsToolbar.Controls.Add(_invokeButton);

            _captureContextButton = CreateButton("Capture", 100, 10, 100);
            _captureContextButton.Height = 30;
            _captureContextButton.BackColor = Color.FromArgb(130, 100, 180);
            _captureContextButton.Click += OnCaptureContextMenu;
            propsToolbar.Controls.Add(_captureContextButton);

            var propsLabel = new Label
            {
                Text = "Properties",
                Location = new Point(205, 16),
                AutoSize = true,
                ForeColor = DarkText,
                Font = new Font("Segoe UI", 9F, FontStyle.Bold)
            };
            propsToolbar.Controls.Add(propsLabel);

            rightPanel.Controls.Add(propsToolbar);

            _mainSplit.Panel2.Controls.Add(rightPanel);

            // Status bar with resize grip
            var statusStrip = new StatusStrip
            {
                BackColor = DarkPanel,
                SizingGrip = true
            };
            var statusLabel = new ToolStripStatusLabel("Ready")
            {
                ForeColor = DarkTextDim,
                Spring = true,
                TextAlign = ContentAlignment.MiddleLeft
            };
            statusStrip.Items.Add(statusLabel);
            _statusLabel = new Label { Text = "Ready" }; // Keep for compatibility

            Controls.Add(_mainSplit);
            Controls.Add(statusStrip);
        }

        private Button CreateButton(string text, int x, int y, int width)
        {
            var button = new Button
            {
                Text = text,
                Location = new Point(x, y),
                Size = new Size(width, 25),
                BackColor = DarkPanel,
                ForeColor = DarkText,
                FlatStyle = FlatStyle.Flat
            };
            button.FlatAppearance.BorderColor = DarkBorder;
            button.FlatAppearance.MouseOverBackColor = DarkHover;
            return button;
        }

        private void LoadMenuTree()
        {
            _menuTree.Nodes.Clear();
            _propertyList.Items.Clear();
            _selectedMenuItem = null;
            _invokeButton.Enabled = false;

            try
            {
                // Find target form if not specified
                if (_targetForm == null || _targetForm.IsDisposed)
                {
                    _targetForm = _reflectionExplorer.FindMainForm();
                }

                if (_targetForm == null)
                {
                    _menuTree.Nodes.Add("Could not find MusicBee main form");
                    _statusLabel.Text = "Error: Could not find target form";
                    return;
                }

                var source = _menuSourceCombo.SelectedItem?.ToString() ?? "All Menus";
                var includeSeparators = _showAllItemsCheck.Checked;

                // Get menu items based on source
                _allMenuItems = new List<MenuItemDetail>();

                if (source == "All Menus" || source == "Main Menu")
                {
                    if (_targetForm.MainMenuStrip != null)
                    {
                        var mainMenuNode = _menuTree.Nodes.Add($"Main Menu: {_targetForm.MainMenuStrip.Name}");
                        mainMenuNode.ForeColor = DarkAccent;
                        mainMenuNode.Tag = _targetForm.MainMenuStrip;

                        var menuTree = _menuWalker.GetMenuTree(_targetForm);
                        foreach (var rootItem in menuTree)
                        {
                            BuildMenuTreeNode(mainMenuNode, rootItem, includeSeparators);
                        }

                        mainMenuNode.Expand();

                        var mainItems = _menuWalker.GetMenuStripItems(_targetForm.MainMenuStrip);
                        _allMenuItems.AddRange(mainItems);
                    }
                }

                if (source == "All Menus" || source == "Context Menus")
                {
                    var contextMenus = _menuWalker.GetContextMenus(_targetForm);

                    if (contextMenus.Count > 0)
                    {
                        var contextRootNode = _menuTree.Nodes.Add($"Context Menus ({contextMenus.Count})");
                        contextRootNode.ForeColor = DarkMenu;

                        foreach (var ctx in contextMenus)
                        {
                            var ctxNode = contextRootNode.Nodes.Add($"{ctx.ContextMenuName} @ {ctx.AttachedTo}");
                            ctxNode.ForeColor = DarkMenu;
                            ctxNode.Tag = ctx;

                            var ctxItems = _menuWalker.GetContextMenuItems(ctx.ContextMenu, ctx.AttachedTo);
                            foreach (var item in ctxItems)
                            {
                                if (!includeSeparators && item.IsSeparator)
                                    continue;

                                var itemNode = ctxNode.Nodes.Add(FormatMenuItemText(item));
                                itemNode.Tag = item;
                                ColorMenuNode(itemNode, item);
                            }

                            _allMenuItems.AddRange(ctxItems);
                        }

                        contextRootNode.Expand();
                    }
                }

                // Get statistics
                var stats = _menuWalker.GetMenuStatistics(_targetForm);
                _statusLabel.Text = $"Menu Items: {stats.TotalMenuItems} | With Handlers: {stats.MenuItemsWithHandlers} | Context Menus: {stats.ContextMenuCount}";
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error loading menu tree");
                _menuTree.Nodes.Add($"Error: {ex.Message}");
                _statusLabel.Text = $"Error: {ex.Message}";
            }
        }

        private void BuildMenuTreeNode(TreeNode parentNode, MenuTreeNode menuNode, bool includeSeparators)
        {
            if (menuNode.IsSeparator && !includeSeparators)
                return;

            var text = menuNode.IsSeparator ? "---" : FormatMenuTreeNodeText(menuNode);
            var node = parentNode.Nodes.Add(text);
            node.Tag = menuNode;

            if (menuNode.IsSeparator)
            {
                node.ForeColor = DarkTextDim;
            }
            else if (menuNode.HasClickHandler)
            {
                node.ForeColor = DarkSuccess;
            }
            else if (!menuNode.Enabled)
            {
                node.ForeColor = DarkTextDim;
            }
            else
            {
                node.ForeColor = DarkText;
            }

            if (menuNode.Children != null)
            {
                foreach (var child in menuNode.Children)
                {
                    BuildMenuTreeNode(node, child, includeSeparators);
                }
            }
        }

        private string FormatMenuTreeNodeText(MenuTreeNode menuNode)
        {
            var text = menuNode.Text ?? menuNode.Name ?? "[unnamed]";

            if (menuNode.ShortcutKeys != Keys.None)
            {
                text += $" [{menuNode.ShortcutKeys}]";
            }

            if (menuNode.Checked)
            {
                text = "[X] " + text;
            }

            if (!menuNode.Enabled)
            {
                text += " (disabled)";
            }

            if (menuNode.HasClickHandler)
            {
                text += " *";
            }

            return text;
        }

        private string FormatMenuItemText(MenuItemDetail item)
        {
            var text = item.Text?.Replace("&", "") ?? item.Name ?? "[unnamed]";

            if (item.ShortcutKeys != Keys.None)
            {
                text += $" [{item.ShortcutKeys}]";
            }

            if (item.Checked)
            {
                text = "[X] " + text;
            }

            if (!item.Enabled)
            {
                text += " (disabled)";
            }

            if (item.HasClickHandler)
            {
                text += " *";
            }

            return text;
        }

        private void ColorMenuNode(TreeNode node, MenuItemDetail item)
        {
            if (item.IsSeparator)
            {
                node.ForeColor = DarkTextDim;
            }
            else if (item.HasClickHandler)
            {
                node.ForeColor = DarkSuccess;
            }
            else if (!item.Enabled)
            {
                node.ForeColor = DarkTextDim;
            }
            else
            {
                node.ForeColor = DarkText;
            }
        }

        private void OnSearchChanged(object sender, EventArgs e)
        {
            var searchText = _searchBox.Text?.ToLowerInvariant();
            if (string.IsNullOrEmpty(searchText) || searchText == "search menu items...")
                return;

            // Search through all items
            var matches = _allMenuItems?.Where(item =>
                (item.Text?.ToLowerInvariant().Contains(searchText) ?? false) ||
                (item.Name?.ToLowerInvariant().Contains(searchText) ?? false) ||
                (item.Path?.ToLowerInvariant().Contains(searchText) ?? false) ||
                (item.ClickHandlerMethodName?.ToLowerInvariant().Contains(searchText) ?? false)
            ).ToList();

            if (matches != null && matches.Count > 0)
            {
                _statusLabel.Text = $"Found {matches.Count} matches";

                // Find and select first match in tree
                foreach (TreeNode node in GetAllNodes(_menuTree.Nodes))
                {
                    if (node.Text.ToLowerInvariant().Contains(searchText))
                    {
                        _menuTree.SelectedNode = node;
                        node.EnsureVisible();
                        break;
                    }
                }
            }
            else
            {
                _statusLabel.Text = "No matches found";
            }
        }

        private IEnumerable<TreeNode> GetAllNodes(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                yield return node;
                foreach (var child in GetAllNodes(node.Nodes))
                {
                    yield return child;
                }
            }
        }

        private void OnMenuItemSelected(object sender, TreeViewEventArgs e)
        {
            _propertyList.Items.Clear();
            _selectedMenuItem = null;
            _invokeButton.Enabled = false;

            var tag = e.Node?.Tag;
            if (tag == null)
            {
                _detailLabel.Text = "Select a menu item to view details";
                return;
            }

            if (tag is MenuTreeNode menuTreeNode && menuTreeNode.MenuItem != null)
            {
                // Convert MenuTreeNode to MenuItemDetail for display
                ShowMenuTreeNodeProperties(menuTreeNode);

                if (!menuTreeNode.IsSeparator)
                {
                    _invokeButton.Enabled = true;
                }
            }
            else if (tag is MenuItemDetail menuItem)
            {
                _selectedMenuItem = menuItem;
                ShowMenuItemProperties(menuItem);

                if (!menuItem.IsSeparator && menuItem.ToolStripItem is ToolStripMenuItem)
                {
                    _invokeButton.Enabled = true;
                }
            }
            else if (tag is ContextMenuInfo ctxInfo)
            {
                ShowContextMenuProperties(ctxInfo);
            }
        }

        private void ShowMenuTreeNodeProperties(MenuTreeNode menuNode)
        {
            AddProperty("Text", menuNode.Text ?? "");
            AddProperty("Name", menuNode.Name ?? "");
            AddProperty("Enabled", menuNode.Enabled.ToString());
            AddProperty("Visible", menuNode.Visible.ToString());
            AddProperty("Checked", menuNode.Checked.ToString());

            if (menuNode.ShortcutKeys != Keys.None)
            {
                AddProperty("ShortcutKeys", menuNode.ShortcutKeys.ToString());
            }

            AddProperty("Has Handler", menuNode.HasClickHandler.ToString());
            AddProperty("Children", menuNode.Children?.Count.ToString() ?? "0");

            // Handler details
            if (menuNode.HasClickHandler && menuNode.MenuItem != null)
            {
                var items = _menuWalker.GetMenuStripItems(null);
                // Try to find in all items
                foreach (var item in _allMenuItems ?? new List<MenuItemDetail>())
                {
                    if (item.ToolStripItem == menuNode.MenuItem)
                    {
                        _selectedMenuItem = item;
                        _detailLabel.Text = $"Handler: {item.ClickHandlerTargetTypeName}.{item.ClickHandlerMethodName}()";
                        break;
                    }
                }
            }
            else
            {
                _detailLabel.Text = "No handler attached";
            }
        }

        private void ShowMenuItemProperties(MenuItemDetail item)
        {
            AddProperty("Path", item.Path ?? "");
            AddProperty("Text", item.Text ?? "");
            AddProperty("Name", item.Name ?? "");
            AddProperty("Type", item.ItemType ?? "");
            AddProperty("Source", item.Source ?? "");
            AddProperty("Enabled", item.Enabled.ToString());
            AddProperty("Visible", item.Visible.ToString());
            AddProperty("Available", item.Available.ToString());

            if (item.ShortcutKeys != Keys.None)
            {
                AddProperty("ShortcutKeys", item.ShortcutKeys.ToString());
            }

            if (!string.IsNullOrEmpty(item.ShortcutKeyDisplayString))
            {
                AddProperty("Shortcut Display", item.ShortcutKeyDisplayString);
            }

            AddProperty("Checked", item.Checked.ToString());
            AddProperty("CheckOnClick", item.CheckOnClick.ToString());
            AddProperty("HasDropDownItems", item.HasDropDownItems.ToString());

            if (item.HasDropDownItems)
            {
                AddProperty("DropDownItemCount", item.DropDownItemCount.ToString());
            }

            AddProperty("Has Handler", item.HasClickHandler.ToString());

            if (item.HasClickHandler)
            {
                AddProperty("Handler Method", item.ClickHandlerMethodName ?? "?");
                AddProperty("Handler Target", item.ClickHandlerTargetTypeName ?? "?");

                _detailLabel.Text = $"Handler:\n{item.ClickHandlerTargetTypeName}.{item.ClickHandlerMethodName}()";
            }
            else
            {
                _detailLabel.Text = "No handler attached";
            }
        }

        private void ShowContextMenuProperties(ContextMenuInfo ctxInfo)
        {
            AddProperty("Name", ctxInfo.ContextMenuName ?? "");
            AddProperty("Attached To", ctxInfo.AttachedTo ?? "");
            AddProperty("Item Count", ctxInfo.ItemCount.ToString());

            _detailLabel.Text = "Context menu - expand to see items";
        }

        private void AddProperty(string name, string value)
        {
            var item = new ListViewItem(new[] { name, value });
            item.ForeColor = DarkText;
            item.BackColor = DarkPanel;
            _propertyList.Items.Add(item);
        }

        private void OnMenuItemDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (_invokeButton.Enabled)
            {
                OnInvokeMenuItem(sender, e);
            }
        }

        private void OnInvokeMenuItem(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = null;

            var selectedNode = _menuTree.SelectedNode;
            if (selectedNode?.Tag is MenuTreeNode menuTreeNode)
            {
                menuItem = menuTreeNode.MenuItem;
            }
            else if (_selectedMenuItem?.ToolStripItem is ToolStripMenuItem tsmi)
            {
                menuItem = tsmi;
            }

            if (menuItem == null)
            {
                MessageBox.Show("Could not find menu item to invoke", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var result = MessageBox.Show(
                $"Click menu item?\n\n" +
                $"Menu: {menuItem.Text}\n\n" +
                $"This will trigger the menu action in MusicBee.",
                "Confirm Click",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (result != DialogResult.Yes)
                return;

            try
            {
                if (_menuWalker.InvokeMenuItem(menuItem))
                {
                    _statusLabel.Text = $"Clicked: {menuItem.Text}";
                    Logger.Info($"User invoked menu item: {menuItem.Text}");
                }
                else
                {
                    MessageBox.Show("Failed to invoke menu item", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error invoking menu item");
                MessageBox.Show(
                    $"Error invoking menu item:\n{ex.Message}",
                    "Invoke Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void OnCaptureContextMenu(object sender, EventArgs e)
        {
            if (_isCapturingContextMenu)
            {
                StopCapture();
                return;
            }

            _isCapturingContextMenu = true;
            _captureContextButton.Text = "Cancel Capture";
            _captureContextButton.BackColor = Color.FromArgb(180, 80, 80);
            _statusLabel.Text = "Right-click on a control in MusicBee to capture its context menu...";

            // Hook global mouse events
            // Note: This is a simplified version - a full implementation would use low-level hooks
            var timer = new Timer { Interval = 100 };
            timer.Tick += (ts, te) =>
            {
                if (!_isCapturingContextMenu)
                {
                    timer.Stop();
                    timer.Dispose();
                    return;
                }

                // Check if any context menu is currently visible via our walker
                // Note: ContextMenuStrip is not a Form, so we check via our captured context menus

                // Also check for ToolStripDropDownMenu
                var contextMenus = _menuWalker.GetContextMenus(_targetForm);
                foreach (var ctx in contextMenus)
                {
                    if (ctx.ContextMenu != null && ctx.ContextMenu.Visible)
                    {
                        CaptureVisibleContextMenu(ctx.ContextMenu);
                        StopCapture();
                        timer.Stop();
                        timer.Dispose();
                        return;
                    }
                }
            };
            timer.Start();

            // Auto-stop after 30 seconds
            var timeoutTimer = new Timer { Interval = 30000 };
            timeoutTimer.Tick += (ts, te) =>
            {
                if (_isCapturingContextMenu)
                {
                    StopCapture();
                    _statusLabel.Text = "Context menu capture timed out";
                }
                timeoutTimer.Stop();
                timeoutTimer.Dispose();
            };
            timeoutTimer.Start();
        }

        private void StopCapture()
        {
            _isCapturingContextMenu = false;
            _captureContextButton.Text = "Capture Context Menu";
            _captureContextButton.BackColor = Color.FromArgb(130, 100, 180);
        }

        private void CaptureVisibleContextMenu(ContextMenuStrip contextMenu)
        {
            try
            {
                var items = _menuWalker.GetContextMenuItems(contextMenu, "Captured");

                var captureNode = _menuTree.Nodes.Add($"CAPTURED: {contextMenu.Name} ({items.Count} items)");
                captureNode.ForeColor = DarkWarning;
                captureNode.Tag = contextMenu;

                foreach (var item in items)
                {
                    var itemNode = captureNode.Nodes.Add(FormatMenuItemText(item));
                    itemNode.Tag = item;
                    ColorMenuNode(itemNode, item);
                }

                captureNode.Expand();
                _menuTree.SelectedNode = captureNode;

                _statusLabel.Text = $"Captured context menu: {contextMenu.Name} with {items.Count} items";
                Logger.Info($"Captured context menu: {contextMenu.Name}");
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error capturing context menu");
                _statusLabel.Text = $"Error capturing: {ex.Message}";
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            _isCapturingContextMenu = false;
            base.OnFormClosing(e);
        }
    }
}
