using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MusicBeePlugin.Clouseau.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

namespace MusicBeePlugin.Clouseau.UI
{
    /// <summary>
    /// Configuration dialog for mbClouseau settings.
    /// Displays current settings with tabs for different configuration areas.
    /// Uses dark theme and integrates with ClouseauSettings.
    /// Supports full editing with Apply/OK/Cancel functionality.
    /// </summary>
    public class SettingsDialog : Form
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // Dark theme colors
        private static readonly Color DarkBackground = Color.FromArgb(30, 30, 30);
        private static readonly Color DarkForeground = Color.FromArgb(220, 220, 220);
        private static readonly Color DarkControlBackground = Color.FromArgb(45, 45, 45);
        private static readonly Color DarkBorder = Color.FromArgb(60, 60, 60);
        private static readonly Color DarkGroupBox = Color.FromArgb(40, 40, 40);
        private static readonly Color AccentColor = Color.FromArgb(76, 175, 80);

        private readonly TabControl _tabControl;
        private readonly Button _okButton;
        private readonly Button _cancelButton;
        private readonly Button _applyButton;
        private readonly string _settingsPath;
        private readonly string _dataPath;
        private ClouseauSettings _settings;
        private ClouseauSettings _originalSettings; // For cancel/revert
        private JObject _rawSettings; // Keep for backward compatibility
        private bool _isDirty; // Track unsaved changes

        // Tab pages
        private TabPage _generalTab;
        private TabPage _metricsTab;
        private TabPage _introspectionTab;
        private TabPage _advancedTab;
        private TabPage _uiTab;
        private TabPage _exportTab;

        /// <summary>
        /// Creates a new SettingsDialog.
        /// </summary>
        /// <param name="settingsPath">Path to the settings.json file.</param>
        public SettingsDialog(string settingsPath)
            : this(settingsPath, Path.GetDirectoryName(settingsPath))
        {
        }

        /// <summary>
        /// Creates a new SettingsDialog with ClouseauSettings integration.
        /// </summary>
        /// <param name="settingsPath">Path to the settings.json file.</param>
        /// <param name="dataPath">Path to the plugin data directory.</param>
        public SettingsDialog(string settingsPath, string dataPath)
        {
            _settingsPath = settingsPath;
            _dataPath = dataPath;

            // Form properties with dark theme
            Text = "mbClouseau Settings";
            Size = new Size(900, 750);
            MinimumSize = new Size(700, 550);
            StartPosition = FormStartPosition.CenterParent;
            FormBorderStyle = FormBorderStyle.Sizable;
            MaximizeBox = true;
            MinimizeBox = false;
            ShowIcon = false;
            ShowInTaskbar = false;
            BackColor = DarkBackground;
            ForeColor = DarkForeground;

            // Tab control with dark theme
            _tabControl = new TabControl
            {
                Dock = DockStyle.Fill,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground
            };

            // Button panel with dark theme
            var buttonPanel = new Panel
            {
                Dock = DockStyle.Bottom,
                Height = 60,
                Padding = new Padding(10),
                BackColor = DarkBackground
            };

            _okButton = new Button
            {
                Text = "OK",
                Width = 90,
                Height = 40,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right,
                DialogResult = DialogResult.OK,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            _okButton.FlatAppearance.BorderColor = DarkBorder;
            _okButton.Click += OnOkClick;

            _cancelButton = new Button
            {
                Text = "Cancel",
                Width = 90,
                Height = 40,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right,
                DialogResult = DialogResult.Cancel,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            _cancelButton.FlatAppearance.BorderColor = DarkBorder;

            _applyButton = new Button
            {
                Text = "Apply",
                Width = 90,
                Height = 40,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right,
                Enabled = false, // Enabled when changes are made
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            _applyButton.FlatAppearance.BorderColor = DarkBorder;
            _applyButton.Click += OnApplyClick;

            // Position buttons
            _cancelButton.Location = new Point(buttonPanel.Width - _cancelButton.Width - 15, 10);
            _applyButton.Location = new Point(_cancelButton.Left - _applyButton.Width - 10, 10);
            _okButton.Location = new Point(_applyButton.Left - _okButton.Width - 10, 10);

            buttonPanel.Controls.Add(_okButton);
            buttonPanel.Controls.Add(_cancelButton);
            buttonPanel.Controls.Add(_applyButton);

            // Layout
            Controls.Add(_tabControl);
            Controls.Add(buttonPanel);

            AcceptButton = _okButton;
            CancelButton = _cancelButton;

            // Handle resize for button positioning
            buttonPanel.Resize += (s, e) =>
            {
                _cancelButton.Location = new Point(buttonPanel.Width - _cancelButton.Width - 15, 10);
                _applyButton.Location = new Point(_cancelButton.Left - _applyButton.Width - 10, 10);
                _okButton.Location = new Point(_applyButton.Left - _okButton.Width - 10, 10);
            };

            // Initialize tabs and load settings
            InitializeTabs();
            LoadSettings();
        }

        /// <summary>
        /// Creates a new SettingsDialog from an existing ClouseauSettings instance.
        /// </summary>
        /// <param name="settings">The ClouseauSettings instance to display.</param>
        /// <param name="dataPath">Path to the plugin data directory.</param>
        public SettingsDialog(ClouseauSettings settings, string dataPath)
            : this(Path.Combine(dataPath, "settings.json"), dataPath)
        {
            _settings = settings;
            ApplySettingsToUI();
        }

        /// <summary>
        /// Initializes the tab pages.
        /// </summary>
        private void InitializeTabs()
        {
            _generalTab = CreateGeneralTab();
            _metricsTab = CreateMetricsTab();
            _introspectionTab = CreateIntrospectionTab();
            _uiTab = CreateUITab();
            _exportTab = CreateExportTab();
            _advancedTab = CreateAdvancedTab();

            _tabControl.TabPages.Add(_generalTab);
            _tabControl.TabPages.Add(_metricsTab);
            _tabControl.TabPages.Add(_introspectionTab);
            _tabControl.TabPages.Add(_uiTab);
            _tabControl.TabPages.Add(_exportTab);
            _tabControl.TabPages.Add(_advancedTab);
        }

        /// <summary>
        /// Creates the General settings tab with dark theme.
        /// </summary>
        private TabPage CreateGeneralTab()
        {
            var tab = new TabPage("General");
            tab.BackColor = DarkBackground;
            tab.ForeColor = DarkForeground;

            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(10), BackColor = DarkBackground, AutoScroll = true };

            // Logging section
            var loggingGroup = new GroupBox
            {
                Text = "Logging",
                Location = new Point(15, 15),
                Size = new Size(820, 200),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var loggingEnabled = CreateEditableCheckBox("Logging Enabled", new Point(20, 35));
            loggingEnabled.Name = "loggingEnabled";
            loggingGroup.Controls.Add(loggingEnabled);

            var levelLabel = new Label { Text = "Log Level:", Location = new Point(20, 75), AutoSize = true, ForeColor = DarkForeground };
            loggingGroup.Controls.Add(levelLabel);
            var levelCombo = CreateLogLevelComboBox(new Point(135, 72));
            levelCombo.Name = "logLevel";
            levelCombo.Width = 155;
            loggingGroup.Controls.Add(levelCombo);

            var fileLogEnabled = CreateEditableCheckBox("File Logging", new Point(20, 115));
            fileLogEnabled.Name = "fileLogEnabled";
            loggingGroup.Controls.Add(fileLogEnabled);

            var maxSizeLabel = new Label { Text = "Max Size (MB):", Location = new Point(20, 155), AutoSize = true, ForeColor = DarkForeground };
            loggingGroup.Controls.Add(maxSizeLabel);
            var maxSizeValue = CreateEditableNumericUpDown(new Point(170, 152), 62, 1, 1000, 50);
            maxSizeValue.Name = "maxLogSize";
            loggingGroup.Controls.Add(maxSizeValue);

            panel.Controls.Add(loggingGroup);

            // Events section
            var eventsGroup = new GroupBox
            {
                Text = "Event Subscription",
                Location = new Point(15, 230),
                Size = new Size(820, 180),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var subscribeAll = CreateEditableCheckBox("Subscribe to All Events", new Point(20, 35));
            subscribeAll.Name = "subscribeAll";
            eventsGroup.Controls.Add(subscribeAll);

            var playerEvents = CreateEditableCheckBox("Player Events", new Point(20, 75));
            playerEvents.Name = "playerEvents";
            eventsGroup.Controls.Add(playerEvents);

            var tagEvents = CreateEditableCheckBox("Tag Events", new Point(200, 75));
            tagEvents.Name = "tagEvents";
            eventsGroup.Controls.Add(tagEvents);

            var downloadEvents = CreateEditableCheckBox("Download Events", new Point(380, 75));
            downloadEvents.Name = "downloadEvents";
            eventsGroup.Controls.Add(downloadEvents);

            var dataStreamEvents = CreateEditableCheckBox("Data Stream Events", new Point(20, 115));
            dataStreamEvents.Name = "dataStreamEvents";
            eventsGroup.Controls.Add(dataStreamEvents);

            panel.Controls.Add(eventsGroup);

            tab.Controls.Add(panel);
            return tab;
        }

        /// <summary>
        /// Creates the Metrics settings tab with dark theme.
        /// </summary>
        private TabPage CreateMetricsTab()
        {
            var tab = new TabPage("Metrics");
            tab.BackColor = DarkBackground;
            tab.ForeColor = DarkForeground;

            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(10), BackColor = DarkBackground, AutoScroll = true };

            // System Metrics section
            var metricsGroup = new GroupBox
            {
                Text = "System Metrics Collection",
                Location = new Point(15, 15),
                Size = new Size(820, 280),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var metricsEnabled = CreateEditableCheckBox("Enable System Metrics", new Point(20, 35));
            metricsEnabled.Name = "metricsEnabled";
            metricsGroup.Controls.Add(metricsEnabled);

            var collectionLabel = new Label { Text = "Collection Interval (ms):", Location = new Point(20, 80), AutoSize = true, ForeColor = DarkForeground };
            metricsGroup.Controls.Add(collectionLabel);
            var collectionValue = CreateEditableNumericUpDown(new Point(232, 77), 130, 100, 60000, 5000);
            collectionValue.Name = "collectionInterval";
            metricsGroup.Controls.Add(collectionValue);

            var logIntervalLabel = new Label { Text = "Log Interval (ms):", Location = new Point(390, 80), AutoSize = true, ForeColor = DarkForeground };
            metricsGroup.Controls.Add(logIntervalLabel);
            var logIntervalValue = CreateEditableNumericUpDown(new Point(560, 77), 130, 1000, 300000, 30000);
            logIntervalValue.Name = "logInterval";
            metricsGroup.Controls.Add(logIntervalValue);

            // Metric types
            var cpuMetrics = CreateEditableCheckBox("CPU Metrics", new Point(20, 130));
            cpuMetrics.Name = "cpuMetrics";
            metricsGroup.Controls.Add(cpuMetrics);

            var memoryMetrics = CreateEditableCheckBox("Memory Metrics", new Point(200, 130));
            memoryMetrics.Name = "memoryMetrics";
            metricsGroup.Controls.Add(memoryMetrics);

            var diskMetrics = CreateEditableCheckBox("Disk Metrics", new Point(400, 130));
            diskMetrics.Name = "diskMetrics";
            metricsGroup.Controls.Add(diskMetrics);

            var networkMetrics = CreateEditableCheckBox("Network Metrics", new Point(20, 170));
            networkMetrics.Name = "networkMetrics";
            metricsGroup.Controls.Add(networkMetrics);

            var clrMetrics = CreateEditableCheckBox("CLR Metrics", new Point(200, 170));
            clrMetrics.Name = "clrMetrics";
            metricsGroup.Controls.Add(clrMetrics);

            var audioMetrics = CreateEditableCheckBox("Audio Metrics", new Point(400, 170));
            audioMetrics.Name = "audioMetrics";
            metricsGroup.Controls.Add(audioMetrics);

            var gpuMetrics = CreateEditableCheckBox("GPU Metrics", new Point(20, 210));
            gpuMetrics.Name = "gpuMetrics";
            metricsGroup.Controls.Add(gpuMetrics);

            panel.Controls.Add(metricsGroup);

            // Alerts section
            var alertsGroup = new GroupBox
            {
                Text = "Alerts",
                Location = new Point(15, 310),
                Size = new Size(820, 100),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var alertsEnabled = CreateEditableCheckBox("Enable Alerts", new Point(20, 35));
            alertsEnabled.Name = "alertsEnabled";
            alertsGroup.Controls.Add(alertsEnabled);

            var alertCountLabel = new Label { Text = "Configured Alerts:", Location = new Point(250, 38), AutoSize = true, ForeColor = DarkForeground };
            alertsGroup.Controls.Add(alertCountLabel);
            var alertCountValue = CreateReadOnlyTextBox(new Point(420, 35), 80);
            alertCountValue.Name = "alertCount";
            alertsGroup.Controls.Add(alertCountValue);

            panel.Controls.Add(alertsGroup);

            tab.Controls.Add(panel);
            return tab;
        }

        /// <summary>
        /// Creates the Introspection settings tab with dark theme.
        /// </summary>
        private TabPage CreateIntrospectionTab()
        {
            var tab = new TabPage("Introspection");
            tab.BackColor = DarkBackground;
            tab.ForeColor = DarkForeground;

            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(10), BackColor = DarkBackground, AutoScroll = true };

            // Debugging section
            var debugGroup = new GroupBox
            {
                Text = "Debugging",
                Location = new Point(15, 15),
                Size = new Size(820, 200),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var debugEnabled = CreateEditableCheckBox("Enable Debugging Features", new Point(20, 35));
            debugEnabled.Name = "debugEnabled";
            debugGroup.Controls.Add(debugEnabled);

            var verboseExceptions = CreateEditableCheckBox("Verbose Exceptions", new Point(20, 75));
            verboseExceptions.Name = "verboseExceptions";
            debugGroup.Controls.Add(verboseExceptions);

            var dumpOnCrash = CreateEditableCheckBox("Dump on Crash", new Point(20, 115));
            dumpOnCrash.Name = "dumpOnCrash";
            debugGroup.Controls.Add(dumpOnCrash);

            var stackTraceLabel = new Label { Text = "Stack Trace Depth:", Location = new Point(280, 77), AutoSize = true, ForeColor = DarkForeground };
            debugGroup.Controls.Add(stackTraceLabel);
            var stackTraceValue = CreateEditableNumericUpDown(new Point(470, 74), 80, 1, 100, 10);
            stackTraceValue.Name = "stackTraceDepth";
            debugGroup.Controls.Add(stackTraceValue);

            var dumpPathLabel = new Label { Text = "Dump Path:", Location = new Point(20, 160), AutoSize = true, ForeColor = DarkForeground };
            debugGroup.Controls.Add(dumpPathLabel);
            var dumpPathValue = CreateEditableTextBox(new Point(125, 157), 565);
            dumpPathValue.Name = "dumpPath";
            debugGroup.Controls.Add(dumpPathValue);

            var browseDumpPath = new Button
            {
                Text = "...",
                Location = new Point(700, 156),
                Size = new Size(40, 25),
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            browseDumpPath.FlatAppearance.BorderColor = DarkBorder;
            browseDumpPath.Click += (s, e) => BrowseForFolder(dumpPathValue);
            debugGroup.Controls.Add(browseDumpPath);

            panel.Controls.Add(debugGroup);

            // Performance section
            var perfGroup = new GroupBox
            {
                Text = "Performance Tracking",
                Location = new Point(15, 230),
                Size = new Size(820, 180),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var perfEnabled = CreateEditableCheckBox("Enable Performance Tracking", new Point(20, 35));
            perfEnabled.Name = "perfEnabled";
            perfGroup.Controls.Add(perfEnabled);

            var trackApiCalls = CreateEditableCheckBox("Track API Calls", new Point(20, 80));
            trackApiCalls.Name = "trackApiCalls";
            perfGroup.Controls.Add(trackApiCalls);

            var trackEvents = CreateEditableCheckBox("Track Event Processing", new Point(250, 80));
            trackEvents.Name = "trackEvents";
            perfGroup.Controls.Add(trackEvents);

            var warnLabel = new Label { Text = "Warn Threshold (ms):", Location = new Point(20, 125), AutoSize = true, ForeColor = DarkForeground };
            perfGroup.Controls.Add(warnLabel);
            var warnValue = CreateEditableNumericUpDown(new Point(220, 122), 110, 1, 10000, 100);
            warnValue.Name = "warnThreshold";
            perfGroup.Controls.Add(warnValue);

            var errorLabel = new Label { Text = "Error Threshold (ms):", Location = new Point(370, 125), AutoSize = true, ForeColor = DarkForeground };
            perfGroup.Controls.Add(errorLabel);
            var errorValue = CreateEditableNumericUpDown(new Point(570, 122), 110, 1, 60000, 500);
            errorValue.Name = "errorThreshold";
            perfGroup.Controls.Add(errorValue);

            panel.Controls.Add(perfGroup);

            tab.Controls.Add(panel);
            return tab;
        }

        /// <summary>
        /// Creates the Advanced settings tab with dark theme.
        /// </summary>
        private TabPage CreateAdvancedTab()
        {
            var tab = new TabPage("Advanced");
            tab.BackColor = DarkBackground;
            tab.ForeColor = DarkForeground;

            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(10), BackColor = DarkBackground, AutoScroll = true };

            // Advanced section
            var advancedGroup = new GroupBox
            {
                Text = "Advanced Settings",
                Location = new Point(15, 15),
                Size = new Size(820, 260),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var bufferLabel = new Label { Text = "Buffer Size:", Location = new Point(20, 40), AutoSize = true, ForeColor = DarkForeground };
            advancedGroup.Controls.Add(bufferLabel);
            var bufferValue = CreateEditableNumericUpDown(new Point(140, 37), 140, 100, 100000, 10000);
            bufferValue.Name = "bufferSize";
            advancedGroup.Controls.Add(bufferValue);

            var flushLabel = new Label { Text = "Flush Interval (ms):", Location = new Point(320, 40), AutoSize = true, ForeColor = DarkForeground };
            advancedGroup.Controls.Add(flushLabel);
            var flushValue = CreateEditableNumericUpDown(new Point(500, 37), 140, 100, 60000, 1000);
            flushValue.Name = "flushInterval";
            advancedGroup.Controls.Add(flushValue);

            var asyncLogging = CreateEditableCheckBox("Async Logging", new Point(20, 85));
            asyncLogging.Name = "asyncLogging";
            advancedGroup.Controls.Add(asyncLogging);

            var highResTimer = CreateEditableCheckBox("High Resolution Timer", new Point(250, 85));
            highResTimer.Name = "highResTimer";
            advancedGroup.Controls.Add(highResTimer);

            var captureEnv = CreateEditableCheckBox("Capture Environment on Startup", new Point(20, 130));
            captureEnv.Name = "captureEnv";
            advancedGroup.Controls.Add(captureEnv);

            var captureAssemblies = CreateEditableCheckBox("Capture Loaded Assemblies", new Point(20, 175));
            captureAssemblies.Name = "captureAssemblies";
            advancedGroup.Controls.Add(captureAssemblies);

            var captureWindows = CreateEditableCheckBox("Capture Windows Version", new Point(350, 130));
            captureWindows.Name = "captureWindows";
            advancedGroup.Controls.Add(captureWindows);

            var captureMB = CreateEditableCheckBox("Capture MusicBee Version", new Point(350, 175));
            captureMB.Name = "captureMB";
            advancedGroup.Controls.Add(captureMB);

            panel.Controls.Add(advancedGroup);

            // Settings file info
            var fileGroup = new GroupBox
            {
                Text = "Settings File",
                Location = new Point(15, 290),
                Size = new Size(820, 120),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var pathLabel = new Label { Text = "Path:", Location = new Point(20, 35), AutoSize = true, ForeColor = DarkForeground };
            fileGroup.Controls.Add(pathLabel);
            var pathValue = CreateReadOnlyTextBox(new Point(80, 32), 685);
            pathValue.Name = "settingsPath";
            pathValue.Text = _settingsPath;
            fileGroup.Controls.Add(pathValue);

            var openButton = new Button
            {
                Text = "Open in Editor",
                Location = new Point(20, 75),
                Width = 140,
                Height = 32,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            openButton.FlatAppearance.BorderColor = DarkBorder;
            openButton.Click += (s, e) =>
            {
                try
                {
                    if (File.Exists(_settingsPath))
                    {
                        System.Diagnostics.Process.Start("notepad.exe", _settingsPath);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Error opening settings file");
                }
            };
            fileGroup.Controls.Add(openButton);

            var reloadButton = new Button
            {
                Text = "Reload",
                Location = new Point(175, 75),
                Width = 100,
                Height = 32,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            reloadButton.FlatAppearance.BorderColor = DarkBorder;
            reloadButton.Click += (s, e) => LoadSettings();
            fileGroup.Controls.Add(reloadButton);

            panel.Controls.Add(fileGroup);

            tab.Controls.Add(panel);
            return tab;
        }

        /// <summary>
        /// Creates the UI settings tab with dark theme.
        /// </summary>
        private TabPage CreateUITab()
        {
            var tab = new TabPage("UI");
            tab.BackColor = DarkBackground;
            tab.ForeColor = DarkForeground;

            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(10), BackColor = DarkBackground, AutoScroll = true };

            // Panel Settings section
            var panelGroup = new GroupBox
            {
                Text = "Panel Display",
                Location = new Point(15, 15),
                Size = new Size(820, 300),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var panelEnabled = CreateEditableCheckBox("Enable Panel View", new Point(20, 40));
            panelEnabled.Name = "panelEnabled";
            panelGroup.Controls.Add(panelEnabled);

            var autoScroll = CreateEditableCheckBox("Auto-scroll Log", new Point(280, 40));
            autoScroll.Name = "autoScroll";
            panelGroup.Controls.Add(autoScroll);

            var maxEntriesLabel = new Label { Text = "Max Displayed Entries:", Location = new Point(20, 90), AutoSize = true, ForeColor = DarkForeground };
            panelGroup.Controls.Add(maxEntriesLabel);
            var maxEntriesValue = CreateEditableNumericUpDown(new Point(235, 87), 84, 100, 10000, 1000);
            maxEntriesValue.Name = "maxDisplayedEntries";
            panelGroup.Controls.Add(maxEntriesValue);

            var refreshLabel = new Label { Text = "Refresh Interval (ms):", Location = new Point(380, 90), AutoSize = true, ForeColor = DarkForeground };
            panelGroup.Controls.Add(refreshLabel);
            var refreshValue = CreateEditableNumericUpDown(new Point(575, 87), 84, 50, 5000, 100);
            refreshValue.Name = "refreshInterval";
            panelGroup.Controls.Add(refreshValue);

            var showTimestamp = CreateEditableCheckBox("Show Timestamp", new Point(20, 140));
            showTimestamp.Name = "showTimestamp";
            panelGroup.Controls.Add(showTimestamp);

            var showCategory = CreateEditableCheckBox("Show Category", new Point(220, 140));
            showCategory.Name = "showCategory";
            panelGroup.Controls.Add(showCategory);

            var showSourceFile = CreateEditableCheckBox("Show Source File", new Point(420, 140));
            showSourceFile.Name = "showSourceFile";
            panelGroup.Controls.Add(showSourceFile);

            var colorByCategory = CreateEditableCheckBox("Color Code by Category", new Point(20, 190));
            colorByCategory.Name = "colorByCategory";
            panelGroup.Controls.Add(colorByCategory);

            var colorByLevel = CreateEditableCheckBox("Color Code by Level", new Point(280, 190));
            colorByLevel.Name = "colorByLevel";
            panelGroup.Controls.Add(colorByLevel);

            panel.Controls.Add(panelGroup);

            tab.Controls.Add(panel);
            return tab;
        }

        /// <summary>
        /// Creates the Export settings tab with dark theme.
        /// </summary>
        private TabPage CreateExportTab()
        {
            var tab = new TabPage("Export");
            tab.BackColor = DarkBackground;
            tab.ForeColor = DarkForeground;

            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(10), BackColor = DarkBackground, AutoScroll = true };

            // Export Settings section
            var exportGroup = new GroupBox
            {
                Text = "Export Settings",
                Location = new Point(15, 15),
                Size = new Size(820, 180),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var exportEnabled = CreateEditableCheckBox("Enable Export", new Point(20, 40));
            exportEnabled.Name = "exportEnabled";
            exportGroup.Controls.Add(exportEnabled);

            var defaultFormatLabel = new Label { Text = "Default Format:", Location = new Point(20, 85), AutoSize = true, ForeColor = DarkForeground };
            exportGroup.Controls.Add(defaultFormatLabel);
            var defaultFormatCombo = CreateExportFormatComboBox(new Point(170, 82));
            defaultFormatCombo.Name = "defaultFormat";
            defaultFormatCombo.Width = 150;
            exportGroup.Controls.Add(defaultFormatCombo);

            var includeMetrics = CreateEditableCheckBox("Include Metrics", new Point(20, 130));
            includeMetrics.Name = "includeMetrics";
            exportGroup.Controls.Add(includeMetrics);

            var includeSystemInfo = CreateEditableCheckBox("Include System Info", new Point(220, 130));
            includeSystemInfo.Name = "includeSystemInfo";
            exportGroup.Controls.Add(includeSystemInfo);

            var compressionEnabled = CreateEditableCheckBox("Enable Compression", new Point(450, 130));
            compressionEnabled.Name = "compressionEnabled";
            exportGroup.Controls.Add(compressionEnabled);

            panel.Controls.Add(exportGroup);

            // Auto-Export section
            var autoExportGroup = new GroupBox
            {
                Text = "Auto-Export",
                Location = new Point(15, 210),
                Size = new Size(820, 150),
                BackColor = DarkGroupBox,
                ForeColor = DarkForeground
            };

            var autoExportEnabled = CreateEditableCheckBox("Enable Auto-Export", new Point(20, 40));
            autoExportEnabled.Name = "autoExportEnabled";
            autoExportGroup.Controls.Add(autoExportEnabled);

            var intervalLabel = new Label { Text = "Interval (minutes):", Location = new Point(280, 43), AutoSize = true, ForeColor = DarkForeground };
            autoExportGroup.Controls.Add(intervalLabel);
            var intervalValue = CreateEditableNumericUpDown(new Point(445, 40), 65, 5, 1440, 60);
            intervalValue.Name = "autoExportInterval";
            autoExportGroup.Controls.Add(intervalValue);

            var autoExportPathLabel = new Label { Text = "Export Path:", Location = new Point(20, 95), AutoSize = true, ForeColor = DarkForeground };
            autoExportGroup.Controls.Add(autoExportPathLabel);
            var autoExportPath = CreateEditableTextBox(new Point(140, 92), 550);
            autoExportPath.Name = "autoExportPath";
            autoExportGroup.Controls.Add(autoExportPath);

            var browseExportPath = new Button
            {
                Text = "...",
                Location = new Point(700, 91),
                Size = new Size(40, 25),
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            browseExportPath.FlatAppearance.BorderColor = DarkBorder;
            browseExportPath.Click += (s, e) => BrowseForFolder(autoExportPath);
            autoExportGroup.Controls.Add(browseExportPath);

            panel.Controls.Add(autoExportGroup);

            tab.Controls.Add(panel);
            return tab;
        }

        /// <summary>
        /// Creates an editable checkbox with dark theme styling.
        /// </summary>
        private CheckBox CreateEditableCheckBox(string text, Point location)
        {
            var cb = new CheckBox
            {
                Text = text,
                Location = location,
                AutoSize = true,
                Enabled = true,
                ForeColor = DarkForeground
            };
            cb.CheckedChanged += OnSettingChanged;
            return cb;
        }

        /// <summary>
        /// Creates an editable textbox with dark theme styling.
        /// </summary>
        private TextBox CreateEditableTextBox(Point location, int width)
        {
            var tb = new TextBox
            {
                Location = location,
                Width = width,
                ReadOnly = false,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                BorderStyle = BorderStyle.FixedSingle
            };
            tb.TextChanged += OnSettingChanged;
            return tb;
        }

        /// <summary>
        /// Creates a read-only textbox with dark theme styling.
        /// </summary>
        private TextBox CreateReadOnlyTextBox(Point location, int width)
        {
            return new TextBox
            {
                Location = location,
                Width = width,
                ReadOnly = true,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                BorderStyle = BorderStyle.FixedSingle
            };
        }

        /// <summary>
        /// Creates an editable numeric up/down with dark theme styling.
        /// </summary>
        private NumericUpDown CreateEditableNumericUpDown(Point location, int width, int min, int max, int defaultValue)
        {
            var nud = new NumericUpDown
            {
                Location = location,
                Width = width,
                Minimum = min,
                Maximum = max,
                Value = defaultValue,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                BorderStyle = BorderStyle.FixedSingle
            };
            nud.ValueChanged += OnSettingChanged;
            return nud;
        }

        /// <summary>
        /// Creates a log level combo box with dark theme styling.
        /// </summary>
        private ComboBox CreateLogLevelComboBox(Point location)
        {
            var cb = new ComboBox
            {
                Location = location,
                Width = 100,
                DropDownStyle = ComboBoxStyle.DropDownList,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            cb.Items.AddRange(new[] { "Trace", "Debug", "Info", "Warn", "Error", "Fatal", "Verbose" });
            cb.SelectedIndexChanged += OnSettingChanged;
            return cb;
        }

        /// <summary>
        /// Creates an export format combo box with dark theme styling.
        /// </summary>
        private ComboBox CreateExportFormatComboBox(Point location)
        {
            var cb = new ComboBox
            {
                Location = location,
                Width = 80,
                DropDownStyle = ComboBoxStyle.DropDownList,
                BackColor = DarkControlBackground,
                ForeColor = DarkForeground,
                FlatStyle = FlatStyle.Flat
            };
            cb.Items.AddRange(new[] { "json", "csv", "txt" });
            cb.SelectedIndexChanged += OnSettingChanged;
            return cb;
        }

        /// <summary>
        /// Opens a folder browser dialog and sets the result to the textbox.
        /// </summary>
        private void BrowseForFolder(TextBox targetTextBox)
        {
            using (var fbd = new FolderBrowserDialog())
            {
                fbd.Description = "Select folder";
                if (!string.IsNullOrEmpty(targetTextBox.Text) && Directory.Exists(targetTextBox.Text))
                {
                    fbd.SelectedPath = targetTextBox.Text;
                }
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    targetTextBox.Text = fbd.SelectedPath;
                }
            }
        }

        /// <summary>
        /// Marks the settings as dirty when any control value changes.
        /// </summary>
        private void OnSettingChanged(object sender, EventArgs e)
        {
            if (!_isDirty)
            {
                _isDirty = true;
                _applyButton.Enabled = true;
                _applyButton.BackColor = AccentColor;
            }
        }

        /// <summary>
        /// Loads settings from the settings file using ClouseauSettings.
        /// </summary>
        private void LoadSettings()
        {
            try
            {
                // Try to load using ClouseauSettings first
                if (!string.IsNullOrEmpty(_dataPath))
                {
                    _settings = ClouseauSettings.Load(_dataPath);
                }

                // Also load raw JSON for backward compatibility with JObject-based UI binding
                if (File.Exists(_settingsPath))
                {
                    var json = File.ReadAllText(_settingsPath);
                    _rawSettings = JObject.Parse(json);
                }
                else
                {
                    Logger.Warn($"Settings file not found: {_settingsPath}");
                    // Use defaults from ClouseauSettings
                    if (_settings == null)
                    {
                        _settings = new ClouseauSettings();
                    }
                }

                ApplySettingsToUI();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error loading settings");
                MessageBox.Show($"Error loading settings:\n{ex.Message}", "Load Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Applies loaded settings to the UI controls using ClouseauSettings.
        /// </summary>
        private void ApplySettingsToUI()
        {
            if (_settings == null) return;

            // Store original settings for cancel/revert
            var json = JsonConvert.SerializeObject(_settings);
            _originalSettings = JsonConvert.DeserializeObject<ClouseauSettings>(json);

            // General tab - use typed ClouseauSettings
            SetCheckBox(_generalTab, "loggingEnabled", _settings.Logging.Enabled);
            SetComboBox(_generalTab, "logLevel", _settings.Logging.Level);
            SetCheckBox(_generalTab, "fileLogEnabled", _settings.Logging.Outputs.FileLog.Enabled);
            SetNumericUpDown(_generalTab, "maxLogSize", _settings.Logging.Outputs.FileLog.MaxSizeMB);
            SetCheckBox(_generalTab, "subscribeAll", _settings.Events.SubscribeAll);
            SetCheckBox(_generalTab, "playerEvents", _settings.Events.NotificationFlags.PlayerEvents);
            SetCheckBox(_generalTab, "tagEvents", _settings.Events.NotificationFlags.TagEvents);
            SetCheckBox(_generalTab, "downloadEvents", _settings.Events.NotificationFlags.DownloadEvents);
            SetCheckBox(_generalTab, "dataStreamEvents", _settings.Events.NotificationFlags.DataStreamEvents);

            // Metrics tab
            SetCheckBox(_metricsTab, "metricsEnabled", _settings.SystemMetrics.Enabled);
            SetNumericUpDown(_metricsTab, "collectionInterval", _settings.SystemMetrics.CollectionIntervalMs);
            SetNumericUpDown(_metricsTab, "logInterval", _settings.SystemMetrics.LogIntervalMs);
            SetCheckBox(_metricsTab, "cpuMetrics", _settings.SystemMetrics.Cpu.Enabled);
            SetCheckBox(_metricsTab, "memoryMetrics", _settings.SystemMetrics.Memory.Enabled);
            SetCheckBox(_metricsTab, "diskMetrics", _settings.SystemMetrics.Disk.Enabled);
            SetCheckBox(_metricsTab, "networkMetrics", _settings.SystemMetrics.Network.Enabled);
            SetCheckBox(_metricsTab, "clrMetrics", _settings.SystemMetrics.Clr.Enabled);
            SetCheckBox(_metricsTab, "audioMetrics", _settings.SystemMetrics.Audio.Enabled);
            SetCheckBox(_metricsTab, "gpuMetrics", false); // Not in settings yet
            SetCheckBox(_metricsTab, "alertsEnabled", _settings.Alerts.Enabled);
            SetTextBox(_metricsTab, "alertCount", _settings.Alerts.Conditions?.Length.ToString() ?? "0");

            // Introspection tab
            SetCheckBox(_introspectionTab, "debugEnabled", _settings.Debugging.Enabled);
            SetCheckBox(_introspectionTab, "verboseExceptions", _settings.Debugging.VerboseExceptions);
            SetCheckBox(_introspectionTab, "dumpOnCrash", _settings.Debugging.DumpOnCrash);
            SetNumericUpDown(_introspectionTab, "stackTraceDepth", _settings.Debugging.StackTraceDepth);
            SetTextBox(_introspectionTab, "dumpPath", _settings.Debugging.DumpPath ?? "");
            SetCheckBox(_introspectionTab, "perfEnabled", _settings.Performance.Enabled);
            SetCheckBox(_introspectionTab, "trackApiCalls", _settings.Performance.TrackApiCalls);
            SetCheckBox(_introspectionTab, "trackEvents", _settings.Performance.TrackEventProcessing);
            SetNumericUpDown(_introspectionTab, "warnThreshold", _settings.Performance.WarnThresholdMs);
            SetNumericUpDown(_introspectionTab, "errorThreshold", _settings.Performance.ErrorThresholdMs);

            // UI tab
            SetCheckBox(_uiTab, "panelEnabled", _settings.UI.Panel.Enabled);
            SetCheckBox(_uiTab, "autoScroll", _settings.UI.Panel.AutoScroll);
            SetNumericUpDown(_uiTab, "maxDisplayedEntries", _settings.UI.Panel.MaxDisplayedEntries);
            SetNumericUpDown(_uiTab, "refreshInterval", _settings.UI.Panel.RefreshIntervalMs);
            SetCheckBox(_uiTab, "showTimestamp", _settings.UI.Panel.ShowTimestamp);
            SetCheckBox(_uiTab, "showCategory", _settings.UI.Panel.ShowCategory);
            SetCheckBox(_uiTab, "showSourceFile", _settings.UI.Panel.ShowSourceFile);
            SetCheckBox(_uiTab, "colorByCategory", _settings.UI.Panel.ColorCodeByCategory);
            SetCheckBox(_uiTab, "colorByLevel", _settings.UI.Panel.ColorCodeByLevel);

            // Export tab
            SetCheckBox(_exportTab, "exportEnabled", _settings.Export.Enabled);
            SetComboBox(_exportTab, "defaultFormat", _settings.Export.DefaultFormat);
            SetCheckBox(_exportTab, "includeMetrics", _settings.Export.IncludeMetrics);
            SetCheckBox(_exportTab, "includeSystemInfo", _settings.Export.IncludeSystemInfo);
            SetCheckBox(_exportTab, "compressionEnabled", _settings.Export.CompressionEnabled);
            SetCheckBox(_exportTab, "autoExportEnabled", _settings.Export.AutoExport.Enabled);
            SetNumericUpDown(_exportTab, "autoExportInterval", _settings.Export.AutoExport.IntervalMinutes);
            SetTextBox(_exportTab, "autoExportPath", _settings.Export.AutoExport.Path ?? "");

            // Advanced tab
            SetNumericUpDown(_advancedTab, "bufferSize", _settings.Advanced.BufferSize);
            SetNumericUpDown(_advancedTab, "flushInterval", _settings.Advanced.FlushIntervalMs);
            SetCheckBox(_advancedTab, "asyncLogging", _settings.Advanced.AsyncLogging);
            SetCheckBox(_advancedTab, "highResTimer", _settings.Advanced.UseHighResolutionTimer);
            SetCheckBox(_advancedTab, "captureEnv", _settings.Advanced.CaptureEnvironmentOnStartup);
            SetCheckBox(_advancedTab, "captureAssemblies", _settings.Advanced.CaptureLoadedAssemblies);
            SetCheckBox(_advancedTab, "captureWindows", _settings.Advanced.CaptureWindowsVersion);
            SetCheckBox(_advancedTab, "captureMB", _settings.Advanced.CaptureMusicBeeVersion);

            // Reset dirty flag after loading
            _isDirty = false;
            _applyButton.Enabled = false;
            _applyButton.BackColor = DarkControlBackground;
        }

        /// <summary>
        /// Sets a checkbox value from a boolean.
        /// </summary>
        private void SetCheckBox(Control parent, string name, bool value)
        {
            var control = FindControl(parent, name) as CheckBox;
            if (control != null)
            {
                control.Checked = value;
            }
        }

        /// <summary>
        /// Sets a textbox value from a string.
        /// </summary>
        private void SetTextBox(Control parent, string name, string value)
        {
            var control = FindControl(parent, name) as TextBox;
            if (control != null)
            {
                control.Text = value ?? "";
            }
        }

        /// <summary>
        /// Sets a NumericUpDown value.
        /// </summary>
        private void SetNumericUpDown(Control parent, string name, int value)
        {
            var control = FindControl(parent, name) as NumericUpDown;
            if (control != null)
            {
                control.Value = Math.Max(control.Minimum, Math.Min(control.Maximum, value));
            }
        }

        /// <summary>
        /// Sets a ComboBox selected item from a string.
        /// </summary>
        private void SetComboBox(Control parent, string name, string value)
        {
            var control = FindControl(parent, name) as ComboBox;
            if (control != null && !string.IsNullOrEmpty(value))
            {
                var index = control.Items.IndexOf(value);
                if (index >= 0)
                {
                    control.SelectedIndex = index;
                }
                else
                {
                    // Try case-insensitive match
                    for (int i = 0; i < control.Items.Count; i++)
                    {
                        if (string.Equals(control.Items[i].ToString(), value, StringComparison.OrdinalIgnoreCase))
                        {
                            control.SelectedIndex = i;
                            break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Gets a checkbox value.
        /// </summary>
        private bool GetCheckBox(Control parent, string name)
        {
            var control = FindControl(parent, name) as CheckBox;
            return control?.Checked ?? false;
        }

        /// <summary>
        /// Gets a textbox value.
        /// </summary>
        private string GetTextBox(Control parent, string name)
        {
            var control = FindControl(parent, name) as TextBox;
            return control?.Text ?? "";
        }

        /// <summary>
        /// Gets a NumericUpDown value.
        /// </summary>
        private int GetNumericUpDown(Control parent, string name)
        {
            var control = FindControl(parent, name) as NumericUpDown;
            return (int)(control?.Value ?? 0);
        }

        /// <summary>
        /// Gets a ComboBox selected item as string.
        /// </summary>
        private string GetComboBox(Control parent, string name)
        {
            var control = FindControl(parent, name) as ComboBox;
            return control?.SelectedItem?.ToString() ?? "";
        }

        /// <summary>
        /// Finds a control by name recursively.
        /// </summary>
        private Control FindControl(Control parent, string name)
        {
            if (parent.Name == name) return parent;

            foreach (Control child in parent.Controls)
            {
                var found = FindControl(child, name);
                if (found != null) return found;
            }

            return null;
        }

        /// <summary>
        /// Handles OK button click.
        /// </summary>
        private void OnOkClick(object sender, EventArgs e)
        {
            if (_isDirty)
            {
                ApplyUIToSettings();
                if (SaveSettings())
                {
                    DialogResult = DialogResult.OK;
                    Close();
                }
            }
            else
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        /// <summary>
        /// Handles Apply button click.
        /// </summary>
        private void OnApplyClick(object sender, EventArgs e)
        {
            ApplyUIToSettings();
            if (SaveSettings())
            {
                _isDirty = false;
                _applyButton.Enabled = false;
                _applyButton.BackColor = DarkControlBackground;
                MessageBox.Show("Settings saved successfully.", "Settings",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// Applies UI control values back to the settings object.
        /// </summary>
        private void ApplyUIToSettings()
        {
            if (_settings == null) return;

            // General tab
            _settings.Logging.Enabled = GetCheckBox(_generalTab, "loggingEnabled");
            _settings.Logging.Level = GetComboBox(_generalTab, "logLevel");
            _settings.Logging.Outputs.FileLog.Enabled = GetCheckBox(_generalTab, "fileLogEnabled");
            _settings.Logging.Outputs.FileLog.MaxSizeMB = GetNumericUpDown(_generalTab, "maxLogSize");
            _settings.Events.SubscribeAll = GetCheckBox(_generalTab, "subscribeAll");
            _settings.Events.NotificationFlags.PlayerEvents = GetCheckBox(_generalTab, "playerEvents");
            _settings.Events.NotificationFlags.TagEvents = GetCheckBox(_generalTab, "tagEvents");
            _settings.Events.NotificationFlags.DownloadEvents = GetCheckBox(_generalTab, "downloadEvents");
            _settings.Events.NotificationFlags.DataStreamEvents = GetCheckBox(_generalTab, "dataStreamEvents");

            // Metrics tab
            _settings.SystemMetrics.Enabled = GetCheckBox(_metricsTab, "metricsEnabled");
            _settings.SystemMetrics.CollectionIntervalMs = GetNumericUpDown(_metricsTab, "collectionInterval");
            _settings.SystemMetrics.LogIntervalMs = GetNumericUpDown(_metricsTab, "logInterval");
            _settings.SystemMetrics.Cpu.Enabled = GetCheckBox(_metricsTab, "cpuMetrics");
            _settings.SystemMetrics.Memory.Enabled = GetCheckBox(_metricsTab, "memoryMetrics");
            _settings.SystemMetrics.Disk.Enabled = GetCheckBox(_metricsTab, "diskMetrics");
            _settings.SystemMetrics.Network.Enabled = GetCheckBox(_metricsTab, "networkMetrics");
            _settings.SystemMetrics.Clr.Enabled = GetCheckBox(_metricsTab, "clrMetrics");
            _settings.SystemMetrics.Audio.Enabled = GetCheckBox(_metricsTab, "audioMetrics");
            _settings.Alerts.Enabled = GetCheckBox(_metricsTab, "alertsEnabled");

            // Introspection tab
            _settings.Debugging.Enabled = GetCheckBox(_introspectionTab, "debugEnabled");
            _settings.Debugging.VerboseExceptions = GetCheckBox(_introspectionTab, "verboseExceptions");
            _settings.Debugging.DumpOnCrash = GetCheckBox(_introspectionTab, "dumpOnCrash");
            _settings.Debugging.StackTraceDepth = GetNumericUpDown(_introspectionTab, "stackTraceDepth");
            _settings.Debugging.DumpPath = GetTextBox(_introspectionTab, "dumpPath");
            _settings.Performance.Enabled = GetCheckBox(_introspectionTab, "perfEnabled");
            _settings.Performance.TrackApiCalls = GetCheckBox(_introspectionTab, "trackApiCalls");
            _settings.Performance.TrackEventProcessing = GetCheckBox(_introspectionTab, "trackEvents");
            _settings.Performance.WarnThresholdMs = GetNumericUpDown(_introspectionTab, "warnThreshold");
            _settings.Performance.ErrorThresholdMs = GetNumericUpDown(_introspectionTab, "errorThreshold");

            // UI tab
            _settings.UI.Panel.Enabled = GetCheckBox(_uiTab, "panelEnabled");
            _settings.UI.Panel.AutoScroll = GetCheckBox(_uiTab, "autoScroll");
            _settings.UI.Panel.MaxDisplayedEntries = GetNumericUpDown(_uiTab, "maxDisplayedEntries");
            _settings.UI.Panel.RefreshIntervalMs = GetNumericUpDown(_uiTab, "refreshInterval");
            _settings.UI.Panel.ShowTimestamp = GetCheckBox(_uiTab, "showTimestamp");
            _settings.UI.Panel.ShowCategory = GetCheckBox(_uiTab, "showCategory");
            _settings.UI.Panel.ShowSourceFile = GetCheckBox(_uiTab, "showSourceFile");
            _settings.UI.Panel.ColorCodeByCategory = GetCheckBox(_uiTab, "colorByCategory");
            _settings.UI.Panel.ColorCodeByLevel = GetCheckBox(_uiTab, "colorByLevel");

            // Export tab
            _settings.Export.Enabled = GetCheckBox(_exportTab, "exportEnabled");
            _settings.Export.DefaultFormat = GetComboBox(_exportTab, "defaultFormat");
            _settings.Export.IncludeMetrics = GetCheckBox(_exportTab, "includeMetrics");
            _settings.Export.IncludeSystemInfo = GetCheckBox(_exportTab, "includeSystemInfo");
            _settings.Export.CompressionEnabled = GetCheckBox(_exportTab, "compressionEnabled");
            _settings.Export.AutoExport.Enabled = GetCheckBox(_exportTab, "autoExportEnabled");
            _settings.Export.AutoExport.IntervalMinutes = GetNumericUpDown(_exportTab, "autoExportInterval");
            _settings.Export.AutoExport.Path = GetTextBox(_exportTab, "autoExportPath");

            // Advanced tab
            _settings.Advanced.BufferSize = GetNumericUpDown(_advancedTab, "bufferSize");
            _settings.Advanced.FlushIntervalMs = GetNumericUpDown(_advancedTab, "flushInterval");
            _settings.Advanced.AsyncLogging = GetCheckBox(_advancedTab, "asyncLogging");
            _settings.Advanced.UseHighResolutionTimer = GetCheckBox(_advancedTab, "highResTimer");
            _settings.Advanced.CaptureEnvironmentOnStartup = GetCheckBox(_advancedTab, "captureEnv");
            _settings.Advanced.CaptureLoadedAssemblies = GetCheckBox(_advancedTab, "captureAssemblies");
            _settings.Advanced.CaptureWindowsVersion = GetCheckBox(_advancedTab, "captureWindows");
            _settings.Advanced.CaptureMusicBeeVersion = GetCheckBox(_advancedTab, "captureMB");
        }

        /// <summary>
        /// Gets the current settings.
        /// </summary>
        public ClouseauSettings Settings => _settings;

        /// <summary>
        /// Gets the path to the settings file.
        /// </summary>
        public string SettingsPath => _settingsPath;

        /// <summary>
        /// Gets the path to the plugin data directory.
        /// </summary>
        public string DataPath => _dataPath;

        /// <summary>
        /// Saves the current settings to file.
        /// </summary>
        /// <returns>True if save was successful, false otherwise.</returns>
        public bool SaveSettings()
        {
            if (_settings == null || string.IsNullOrEmpty(_dataPath))
            {
                return false;
            }

            try
            {
                _settings.Save(_dataPath);
                Logger.Info("Settings saved successfully to {0}", _settingsPath);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error saving settings");
                MessageBox.Show($"Error saving settings:\n{ex.Message}", "Save Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// Reloads settings from file.
        /// </summary>
        public void ReloadSettings()
        {
            LoadSettings();
        }
    }
}
