using System.Collections.ObjectModel;

using System.ComponentModel;

using System.IO;

using System.Runtime.CompilerServices;

using System.Windows;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using NexusShell.Controls.Dialogs;

using NexusShell.Models;

using NexusShell.Services;

using NexusShell.Services.ControlCenter;

using NexusShell.Services.Diagnostics;

using NexusShell.Services.Identity;

using NexusShell.Services.Policy;

using NexusShell.Services.Workspace;



namespace NexusShell.ViewModels;



public sealed class NexusSettingsViewModel : INotifyPropertyChanged

{

    private readonly LockdownService _lockdown;

    private readonly NexusPlatformLockService _platformLock;

    private readonly UpdateService _updateService;

    private readonly UserSettingsService _userSettings;

    private readonly ThemeService _themeService;

    private readonly DisplaySettingsService _displaySettings;

    private readonly ProfileService _profile;

    private readonly NexusDeviceInfoService _deviceInfo;

    private readonly NexusNetworkInfoService _networkInfo;

    private readonly NexusAudioService _audio;

    private readonly NexusBluetoothInfoService _bluetooth;

    private readonly NexusPrinterInfoService _printers;

    private readonly NexusIdentityService _identity;

    private readonly NexusControlCenterService _controlCenter;

    private readonly NexusPolicyService _policy;

    private readonly NexusDefaultAppsService _defaultApps;

    private readonly DiagnosticsService _diagnostics;

    private readonly PerformanceMonitorService _performance;

    private readonly WorkspaceWindowManager _workspaceWindows;

    private readonly ClientVersionInfo _clientVersion;



    private string _selectedTheme = "dark";

    private string _selectedAccent = "auto";

    private string _animationIntensity = "normal";

    private ImageSource? _wallpaperPreview;

    private bool _shellFullscreen = true;

    private bool _hideWindowsTaskbar = true;

    private bool _spanAllMonitors = true;

    private bool _performanceMode;

    private bool _reducedMotionWhenInactive = true;

    private string _diagnosticsStatusMessage = string.Empty;

    private string _diagnosticsEventsSummary = "—";

    private MonitorSettingsItem? _selectedMonitor;

    private DisplayModeInfo? _selectedResolution;

    private string _statusMessage = string.Empty;

    private NexusSettingsSection _selectedSection = NexusSettingsSection.General;

    private string _infoPanelTitle = "Generelt";

    private string _infoPanelBody = "Nexus Shell-indstillinger styres her — ikke Windows Settings.";

    private int _audioVolume = 50;

    private bool _isCheckingUpdates;

    private string _activeNetwork = "—";

    private string _ipAddress = "—";

    private string _signalStrength = "—";

    private string _audioOutputDevice = "—";

    private string _bluetoothStatus = "—";

    private string _cpuName = "—";

    private string _ramLabel = "—";

    private string _diskLabel = "—";

    private string _gpuName = "—";

    private string _displayScalingLabel = "—";

    private string _accountName = "—";

    private string _accountRole = "—";

    private string _accountSession = "—";

    private string _accountEmail = "—";

    private string _buildChannel = "POC";

    private string _latestVersionLabel = "—";

    private string _identityUser = "—";

    private string _identityOrganization = "—";

    private string _identityDeviceId = "—";

    private string _identityStatus = "—";

    private string _identityEnrollmentDate = "—";

    private string _identityTrustStatus = "—";

    private string _controlCenterSource = "Lokal";

    private string _controlCenterSummary = "—";

    private string _controlCenterTrustSummary = "—";

    private string _controlCenterPending = "—";

    private string _controlCenterOnlineCount = "0";
    private string _controlCenterOfflineCount = "0";
    private string _controlCenterWarningCount = "0";
    private string _controlCenterCriticalCount = "0";
    private string _controlCenterPresenceSource = "—";
    private System.Windows.Threading.DispatcherTimer? _controlCenterPollTimer;



    public NexusSettingsViewModel(

        LockdownService lockdown,

        NexusPlatformLockService platformLock,

        UpdateService updateService,

        UserSettingsService userSettings,

        ThemeService themeService,

        DisplaySettingsService displaySettings,

        ProfileService profile,

        NexusDeviceInfoService deviceInfo,

        NexusNetworkInfoService networkInfo,

        NexusAudioService audio,

        NexusBluetoothInfoService bluetooth,

        NexusPrinterInfoService printers,

        NexusIdentityService identity,

        NexusControlCenterService controlCenter,

        NexusPolicyService policy,

        NexusDefaultAppsService defaultApps,

        DiagnosticsService diagnostics,

        PerformanceMonitorService performance,

        WorkspaceWindowManager workspaceWindows,

        ClientVersionInfo clientVersion)

    {

        _lockdown = lockdown;

        _platformLock = platformLock;

        _updateService = updateService;

        _userSettings = userSettings;

        _themeService = themeService;

        _displaySettings = displaySettings;

        _profile = profile;

        _deviceInfo = deviceInfo;

        _networkInfo = networkInfo;

        _audio = audio;

        _bluetooth = bluetooth;

        _printers = printers;

        _identity = identity;

        _controlCenter = controlCenter;

        _policy = policy;

        _defaultApps = defaultApps;

        _diagnostics = diagnostics;

        _performance = performance;

        _workspaceWindows = workspaceWindows;

        _clientVersion = clientVersion;



        Monitors = [];

        VisibleNavItems = new ObservableCollection<NexusSettingsNavItem>();

        _allNavItems =

        [

            new NexusSettingsNavItem { Section = NexusSettingsSection.General, Title = "Generelt", IconPath = "M12,3 L3,7 L3,17 L12,21 L21,17 L21,7 Z", InfoHint = "Shell-adfærd og Nexus lockdown." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Appearance, Title = "Udseende", IconPath = "M12,2 A10,10 0 1,1 12,22 A10,10 0 1,1 12,2 M12,6 A6,6 0 1,0 12,18 A6,6 0 1,0 12,6", InfoHint = "Tema, accent og baggrund." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Display, Title = "Skærm", IconPath = "M3,5 L21,5 L21,15 L3,15 Z M8,19 L16,19 M12,15 L12,19", InfoHint = "Opløsning og skalering (læsning i POC)." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Audio, Title = "Lyd", IconPath = "M11,5 L6,9 L2,9 L2,15 L6,15 L11,19 Z M15,9 A4,4 0 0,1 15,15 A4,4 0 0,1 15,9", InfoHint = "Output og lydstyrke." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Network, Title = "Netværk", IconPath = "M5,12 A7,7 0 0,1 19,12 M8,12 A4,4 0 0,1 16,12 M12,12 A1,1 0 0,1 12,12", InfoHint = "Aktiv forbindelse (læsning i POC)." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Bluetooth, Title = "Bluetooth", IconPath = "M7,7 L17,17 M17,7 L7,17 M12,3 L12,21", InfoHint = "Parrede enheder (læsning i POC)." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Devices, Title = "Enheder", IconPath = "M4,6 L20,6 L20,18 L4,18 Z M8,20 L16,20", InfoHint = "Hardware læses lokalt." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Printers, Title = "Printere", IconPath = "M6,9 L18,9 L18,15 L6,15 Z M6,15 L6,19 L18,19 L18,15 M8,5 L16,5 L16,9 L8,9 Z", InfoHint = "Installerede printere." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Updates, Title = "Nexus Updates", IconPath = "M12,3 L12,7 M12,17 L12,21 M4.2,4.2 L7,7 M17,17 L19.8,19.8 M3,12 L7,12 M17,12 L21,12 M4.2,19.8 L7,17 M17,7 L19.8,4.2", InfoHint = "Opdateringskanal og version." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Account, Title = "Nexus Konto", IconPath = "M12,12 A4,4 0 1,0 12,12 M4,20 A8,8 0 0,1 20,20", InfoHint = "Profil og session." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.Identity, Title = "Nexus Identity", IconPath = "M12,2 L12,6 M12,18 L12,22 M4.2,4.2 L7,7 M17,17 L19.8,19.8 M2,12 L6,12 M18,12 L22,12", InfoHint = "Enhedsidentitet og enrollment." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.ControlCenter, Title = "Control Center", IconPath = "M4,4 L20,4 L20,10 L4,10 Z M4,14 L20,14 L20,20 L4,20 Z", InfoHint = "Platform dashboard (lokal + remote POC)." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.DefaultApps, Title = "Nexus Default Apps", IconPath = "M6,4 L14,4 L18,8 L18,20 L6,20 Z M14,4 L14,8 L18,8 M8,13 L16,13", InfoHint = "Standard Nexus-apps pr. filtype (JSON — ikke Windows registry)." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.DeveloperDiagnostics, Title = "Developer / Diagnostik", IconPath = "M4,4 L20,4 L20,10 L4,10 Z M4,14 L20,14 L20,20 L4,20 Z M8,7 L8,7", InfoHint = "Performance HUD, sessions og eksport (POC)." },

            new NexusSettingsNavItem { Section = NexusSettingsSection.About, Title = "Om Nexus", IconPath = "M12,2 A10,10 0 1,1 12,22 A10,10 0 1,1 12,2 M12,8 L12,8 M11,12 L12,12 L12,16 L13,16", InfoHint = "Version og build." },

        ];

        PairedBluetoothDevices = [];

        InstalledPrinters = [];
        ControlCenterDevices = new ObservableCollection<NexusControlCenterDevicePresenceRow>();

        DefaultAppPreferences = new ObservableCollection<NexusDefaultAppPreferenceRow>();

        AvailableDefaultApps = NexusFileAssociations.GetAvailableApps();

        DefaultAppsStoragePath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "NinjaNexus",
            "default-apps.json");



        CloseCommand = new RelayCommand(_ => CloseRequested?.Invoke(this, EventArgs.Empty));

        SaveCommand = new RelayCommand(_ => SaveSettings());

        BrowseWallpaperCommand = new RelayCommand(_ => BrowseWallpaper());

        ResetWallpaperCommand = new RelayCommand(_ => ResetWallpaper());

        ApplyDisplayCommand = new RelayCommand(_ => ApplyDisplaySettings(), _ => SelectedMonitor is not null && SelectedResolution is not null);

        RefreshMonitorsCommand = new RelayCommand(_ => RefreshMonitors());

        RefreshSectionCommand = new RelayCommand(_ => RefreshActiveSection());

        OpenUpdateInfoCommand = new RelayCommand(_ => OpenUpdateInfoRequested?.Invoke(this, EventArgs.Empty));

        OpenNexusConsoleCommand = new RelayCommand(_ => OpenNexusConsoleRequested?.Invoke(this, EventArgs.Empty), _ => CanOpenNexusConsole);

        UnlockWindowsCommand = new RelayCommand(_ => RequestWindowsUnlock?.Invoke(this, EventArgs.Empty));

        LockWindowsCommand = new RelayCommand(_ => LockWindows(), _ => !_platformLock.IsWindowsLocked);

        StartDiagnosticsSessionCommand = new RelayCommand(_ => StartDiagnosticsSession());

        StopDiagnosticsSessionCommand = new RelayCommand(_ => StopDiagnosticsSession());

        ExportDiagnosticsCommand = new RelayCommand(_ => ExportDiagnosticsAsync());

        SendDiagnosticsCommand = new RelayCommand(_ => SendDiagnosticsAsync());

        OpenDiagnosticsLogsCommand = new RelayCommand(_ => _diagnostics.OpenLogsFolder());

        CopyDiagnosticsInfoCommand = new RelayCommand(_ => CopyDiagnosticsInfo());

        SelectSectionCommand = new RelayCommand(p => SelectSection(p));

        CheckUpdatesCommand = new RelayCommand(async _ => await CheckUpdatesAsync(), _ => !IsCheckingUpdates);

        DownloadAndInstallUpdateCommand = new RelayCommand(
            async _ => await DownloadAndInstallUpdateAsync(),
            _ => CanDownloadAndInstallUpdate);

        _policy.PolicyChanged += (_, _) => RefreshVisibleNavItems();

        RefreshVisibleNavItems();

        LoadFromSettings();

        LoadDefaultAppPreferences();

    }



    public event PropertyChangedEventHandler? PropertyChanged;

    public event EventHandler? CloseRequested;

    public event EventHandler? OpenUpdateInfoRequested;

    public event EventHandler? OpenNexusConsoleRequested;

    public event EventHandler? RequestWindowsUnlock;

    public event EventHandler? AppearanceChanged;

    public event EventHandler? ShellSettingsChanged;



    private readonly IReadOnlyList<NexusSettingsNavItem> _allNavItems;

    public ObservableCollection<NexusSettingsNavItem> VisibleNavItems { get; }

    public ObservableCollection<MonitorSettingsItem> Monitors { get; }

    public ObservableCollection<string> PairedBluetoothDevices { get; }

    public ObservableCollection<NexusPrinterInfo> InstalledPrinters { get; }



    public NexusSettingsSection SelectedSection

    {

        get => _selectedSection;

        set

        {

            if (_selectedSection == value)

            {

                return;

            }



            _selectedSection = value;

            OnPropertyChanged();

            UpdateInfoPanel();

            RefreshActiveSection();

        }

    }



    public string InfoPanelTitle

    {

        get => _infoPanelTitle;

        private set { _infoPanelTitle = value; OnPropertyChanged(); }

    }



    public string InfoPanelBody

    {

        get => _infoPanelBody;

        private set { _infoPanelBody = value; OnPropertyChanged(); }

    }



    public string SelectedTheme

    {

        get => _selectedTheme;

        set

        {

            if (string.Equals(_selectedTheme, value, StringComparison.OrdinalIgnoreCase))

            {

                return;

            }

            _selectedTheme = value;

            OnPropertyChanged();

            OnPropertyChanged(nameof(IsDarkTheme));

            OnPropertyChanged(nameof(IsLightTheme));

            ApplyThemeLive();

        }

    }



    public bool IsDarkTheme

    {

        get => !string.Equals(SelectedTheme, "light", StringComparison.OrdinalIgnoreCase);

        set { if (value) SelectedTheme = "dark"; }

    }



    public bool IsLightTheme

    {

        get => string.Equals(SelectedTheme, "light", StringComparison.OrdinalIgnoreCase);

        set { if (value) SelectedTheme = "light"; }

    }



    public string SelectedAccent

    {

        get => _selectedAccent;

        set

        {

            if (string.Equals(_selectedAccent, value, StringComparison.OrdinalIgnoreCase))

            {

                return;

            }

            _selectedAccent = value;

            OnPropertyChanged();

            OnPropertyChanged(nameof(IsAccentPurple));

            OnPropertyChanged(nameof(IsAccentCyan));

            OnPropertyChanged(nameof(IsAccentAuto));

            ApplyThemeLive();

        }

    }



    private void ApplyThemeLive()

    {

        _userSettings.Current.Theme = SelectedTheme;

        _userSettings.Current.AccentColor = SelectedAccent;

        _themeService.Apply(SelectedTheme, accentColor: SelectedAccent);

        AppearanceChanged?.Invoke(this, EventArgs.Empty);

    }



    public bool IsAccentPurple

    {

        get => string.Equals(SelectedAccent, "purple", StringComparison.OrdinalIgnoreCase);

        set { if (value) SelectedAccent = "purple"; }

    }



    public bool IsAccentCyan

    {

        get => string.Equals(SelectedAccent, "cyan", StringComparison.OrdinalIgnoreCase);

        set { if (value) SelectedAccent = "cyan"; }

    }



    public bool IsAccentAuto

    {

        get => string.Equals(SelectedAccent, "auto", StringComparison.OrdinalIgnoreCase);

        set { if (value) SelectedAccent = "auto"; }

    }



    public string AnimationIntensity

    {

        get => _animationIntensity;

        set

        {

            _animationIntensity = value;

            OnPropertyChanged();

            OnPropertyChanged(nameof(IsAnimationLow));

            OnPropertyChanged(nameof(IsAnimationNormal));

            OnPropertyChanged(nameof(IsAnimationHigh));

        }

    }



    public bool IsAnimationLow

    {

        get => string.Equals(AnimationIntensity, "low", StringComparison.OrdinalIgnoreCase);

        set { if (value) AnimationIntensity = "low"; }

    }



    public bool IsAnimationNormal

    {

        get => string.Equals(AnimationIntensity, "normal", StringComparison.OrdinalIgnoreCase);

        set { if (value) AnimationIntensity = "normal"; }

    }



    public bool IsAnimationHigh

    {

        get => string.Equals(AnimationIntensity, "high", StringComparison.OrdinalIgnoreCase);

        set { if (value) AnimationIntensity = "high"; }

    }



    public ImageSource? WallpaperPreview

    {

        get => _wallpaperPreview;

        private set { _wallpaperPreview = value; OnPropertyChanged(); }

    }



    public bool ShellFullscreen

    {

        get => _shellFullscreen;

        set { _shellFullscreen = value; OnPropertyChanged(); }

    }



    public bool HideWindowsTaskbar

    {

        get => _hideWindowsTaskbar;

        set { _hideWindowsTaskbar = value; OnPropertyChanged(); }

    }



    public bool SpanAllMonitors

    {

        get => _spanAllMonitors;

        set { _spanAllMonitors = value; OnPropertyChanged(); }

    }

    public bool PerformanceMode
    {
        get => _performanceMode;
        set { _performanceMode = value; OnPropertyChanged(); }
    }

    public bool ReducedMotionWhenInactive
    {
        get => _reducedMotionWhenInactive;
        set { _reducedMotionWhenInactive = value; OnPropertyChanged(); }
    }

    public bool ShowDeveloperDiagnosticsSection => _lockdown.DeveloperConsoleEnabled;

    public string DiagnosticsUptimeLabel => FormatUptime(_diagnostics.Uptime);

    public string DiagnosticsCpuLabel => $"{_performance.CpuPercent}%";

    public string DiagnosticsMemoryLabel => $"{_performance.MemoryPercent}%";

    public string DiagnosticsUiLatencyLabel => $"{_performance.AverageUiLatencyMs} ms";

    public string DiagnosticsApiLatencyLabel => $"{_performance.AverageApiLatencyMs} ms";

    public string DiagnosticsActiveWindowsLabel => _workspaceWindows.ActiveWindows.Count.ToString();

    public string DiagnosticsTimersLabel
    {
        get
        {
            var timers = _diagnostics.ActiveTimers;
            return timers.Count == 0
                ? "Ingen aktive timer registreret"
                : string.Join(" · ", timers.Take(6).Select(t => $"{t.Name} {t.Interval.TotalSeconds:0.#}s"));
        }
    }

    public string DiagnosticsSessionLabel => _diagnostics.ActiveSession?.SessionId ?? "Ingen aktiv session";

    public string DiagnosticsEventsSummary
    {
        get => _diagnosticsEventsSummary;
        private set { _diagnosticsEventsSummary = value; OnPropertyChanged(); }
    }

    public string DiagnosticsStatusMessage
    {
        get => _diagnosticsStatusMessage;
        private set { _diagnosticsStatusMessage = value; OnPropertyChanged(); }
    }



    public MonitorSettingsItem? SelectedMonitor

    {

        get => _selectedMonitor;

        set

        {

            _selectedMonitor = value;

            OnPropertyChanged();

            SelectedResolution = value?.Modes.FirstOrDefault();

            UpdateDisplayScaling();

        }

    }



    public DisplayModeInfo? SelectedResolution

    {

        get => _selectedResolution;

        set { _selectedResolution = value; OnPropertyChanged(); }

    }



    public string DisplayScalingLabel

    {

        get => _displayScalingLabel;

        private set { _displayScalingLabel = value; OnPropertyChanged(); }

    }



    public string StatusMessage

    {

        get => _statusMessage;

        private set { _statusMessage = value; OnPropertyChanged(); }

    }



    public int AudioVolume

    {

        get => _audioVolume;

        set

        {

            var clamped = Math.Clamp(value, 0, 100);

            if (_audioVolume == clamped)

            {

                return;

            }



            _audioVolume = clamped;

            OnPropertyChanged();

            if (_audio.TrySetVolumePercent(clamped))

            {

                StatusMessage = $"Lydstyrke sat til {clamped}%.";

            }

        }

    }



    public string AudioOutputDevice

    {

        get => _audioOutputDevice;

        private set { _audioOutputDevice = value; OnPropertyChanged(); }

    }



    public string ActiveNetwork

    {

        get => _activeNetwork;

        private set { _activeNetwork = value; OnPropertyChanged(); }

    }



    public string IpAddress

    {

        get => _ipAddress;

        private set { _ipAddress = value; OnPropertyChanged(); }

    }



    public string SignalStrength

    {

        get => _signalStrength;

        private set { _signalStrength = value; OnPropertyChanged(); }

    }



    public string BluetoothStatus

    {

        get => _bluetoothStatus;

        private set { _bluetoothStatus = value; OnPropertyChanged(); }

    }



    public string CpuName

    {

        get => _cpuName;

        private set { _cpuName = value; OnPropertyChanged(); }

    }



    public string RamLabel

    {

        get => _ramLabel;

        private set { _ramLabel = value; OnPropertyChanged(); }

    }



    public string DiskLabel

    {

        get => _diskLabel;

        private set { _diskLabel = value; OnPropertyChanged(); }

    }



    public string GpuName

    {

        get => _gpuName;

        private set { _gpuName = value; OnPropertyChanged(); }

    }



    public string AccountName

    {

        get => _accountName;

        private set { _accountName = value; OnPropertyChanged(); }

    }



    public string AccountRole

    {

        get => _accountRole;

        private set { _accountRole = value; OnPropertyChanged(); }

    }



    public string AccountSession

    {

        get => _accountSession;

        private set { _accountSession = value; OnPropertyChanged(); }

    }



    public string AccountEmail

    {

        get => _accountEmail;

        private set { _accountEmail = value; OnPropertyChanged(); }

    }



    public string BuildChannel

    {

        get => _buildChannel;

        private set { _buildChannel = value; OnPropertyChanged(); }

    }



    public string LatestVersionLabel

    {

        get => _latestVersionLabel;

        private set { _latestVersionLabel = value; OnPropertyChanged(); }

    }



    public string IdentityUser

    {

        get => _identityUser;

        private set { _identityUser = value; OnPropertyChanged(); }

    }



    public string IdentityOrganization

    {

        get => _identityOrganization;

        private set { _identityOrganization = value; OnPropertyChanged(); }

    }



    public string IdentityDeviceId

    {

        get => _identityDeviceId;

        private set { _identityDeviceId = value; OnPropertyChanged(); }

    }



    public string IdentityStatus

    {

        get => _identityStatus;

        private set { _identityStatus = value; OnPropertyChanged(); }

    }



    public string IdentityEnrollmentDate

    {

        get => _identityEnrollmentDate;

        private set { _identityEnrollmentDate = value; OnPropertyChanged(); }

    }



    public string IdentityTrustStatus

    {

        get => _identityTrustStatus;

        private set { _identityTrustStatus = value; OnPropertyChanged(); }

    }

    public ObservableCollection<NexusControlCenterDevicePresenceRow> ControlCenterDevices { get; }

    public ObservableCollection<NexusDefaultAppPreferenceRow> DefaultAppPreferences { get; }

    public IReadOnlyList<NexusDefaultAppOption> AvailableDefaultApps { get; }

    public string DefaultAppsStoragePath { get; }

    public string ControlCenterOnlineCount
    {
        get => _controlCenterOnlineCount;
        private set { _controlCenterOnlineCount = value; OnPropertyChanged(); }
    }

    public string ControlCenterOfflineCount
    {
        get => _controlCenterOfflineCount;
        private set { _controlCenterOfflineCount = value; OnPropertyChanged(); }
    }

    public string ControlCenterWarningCount
    {
        get => _controlCenterWarningCount;
        private set { _controlCenterWarningCount = value; OnPropertyChanged(); }
    }

    public string ControlCenterCriticalCount
    {
        get => _controlCenterCriticalCount;
        private set { _controlCenterCriticalCount = value; OnPropertyChanged(); }
    }

    public string ControlCenterPresenceSource
    {
        get => _controlCenterPresenceSource;
        private set { _controlCenterPresenceSource = value; OnPropertyChanged(); }
    }

    public string ControlCenterSource

    {

        get => _controlCenterSource;

        private set { _controlCenterSource = value; OnPropertyChanged(); }

    }

    public string ControlCenterSummary

    {

        get => _controlCenterSummary;

        private set { _controlCenterSummary = value; OnPropertyChanged(); }

    }

    public string ControlCenterTrustSummary

    {

        get => _controlCenterTrustSummary;

        private set { _controlCenterTrustSummary = value; OnPropertyChanged(); }

    }

    public string ControlCenterPending

    {

        get => _controlCenterPending;

        private set { _controlCenterPending = value; OnPropertyChanged(); }

    }

    public string PlatformLockStatusLabel => _platformLock.StatusLabel;

    public bool IsWindowsLocked => _platformLock.IsWindowsLocked;



    public bool IsCheckingUpdates

    {

        get => _isCheckingUpdates;

        private set
        {
            _isCheckingUpdates = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(IsNotCheckingUpdates));
            OnPropertyChanged(nameof(CanDownloadAndInstallUpdate));
            CommandManager.InvalidateRequerySuggested();
        }

    }

    public bool IsNotCheckingUpdates => !IsCheckingUpdates;

    public bool CanDownloadAndInstallUpdate =>
        !IsCheckingUpdates
        && _updateService.LastResult?.IsUpdateAvailable == true
        && _updateService.FlowState is ClientUpdateFlowState.UpdateFound
            or ClientUpdateFlowState.Failed
            or ClientUpdateFlowState.Stale
            or ClientUpdateFlowState.Cancelled
            or ClientUpdateFlowState.Idle;



    public string MonitorCountLabel => $"{Monitors.Count} skærm{(Monitors.Count == 1 ? "" : "e")} tilsluttet";



    public string LockdownStatusLabel => !_lockdown.IsSafePocEnabled

        ? "Nexus Lockdown Mode: Disabled (not in safe mode)"

        : _lockdown.IsLockdownActive

            ? "Nexus Lockdown Mode: Active"

            : "Nexus Lockdown Mode: Inactive";



    public string SafePocStatus => _lockdown.IsSafePocEnabled ? "Safe POC enabled" : "Safe POC disabled";

    public string AuditLogPath => _lockdown.AuditFilePath;

    public int AllowedAppsCount => _lockdown.AllowedAppsCount;

    public int BlockedAppsCount => _lockdown.BlockedAppsCount;

    public string DeveloperConsoleStatus => _lockdown.DeveloperConsoleEnabled ? "Enabled (POC)" : "Disabled";

    public bool CanOpenNexusConsole =>

        _lockdown.DeveloperConsoleEnabled &&

        _policy.CanAccessConsole();

    public bool AllowWindowsEscape => _lockdown.Config.AllowWindowsEscape;

    public string UpdateStatusSummary => _updateService.StatusSummary;

    public string CurrentVersionLabel => $"{_updateService.CurrentVersion} (build {_updateService.CurrentBuild})";

    public string AboutVersionLabel => _updateService.CurrentVersion;

    public string AboutBuildLabel => _updateService.CurrentBuild.ToString();



    public ICommand CloseCommand { get; }

    public ICommand SaveCommand { get; }

    public ICommand BrowseWallpaperCommand { get; }

    public ICommand ResetWallpaperCommand { get; }

    public ICommand ApplyDisplayCommand { get; }

    public ICommand RefreshMonitorsCommand { get; }

    public ICommand RefreshSectionCommand { get; }

    public ICommand OpenUpdateInfoCommand { get; }

    public ICommand OpenNexusConsoleCommand { get; }

    public ICommand UnlockWindowsCommand { get; }

    public ICommand LockWindowsCommand { get; }

    public ICommand StartDiagnosticsSessionCommand { get; }

    public ICommand StopDiagnosticsSessionCommand { get; }

    public ICommand ExportDiagnosticsCommand { get; }

    public ICommand SendDiagnosticsCommand { get; }

    public ICommand OpenDiagnosticsLogsCommand { get; }

    public ICommand CopyDiagnosticsInfoCommand { get; }

    public ICommand SelectSectionCommand { get; }

    public ICommand CheckUpdatesCommand { get; }

    public ICommand DownloadAndInstallUpdateCommand { get; }



    public void OpenSection(NexusSettingsSection section) => SelectedSection = section;



    public void OpenSection(string? sectionName)

    {

        if (string.IsNullOrWhiteSpace(sectionName))

        {

            return;

        }



        if (Enum.TryParse<NexusSettingsSection>(sectionName, ignoreCase: true, out var section))

        {

            OpenSection(section);

        }

    }



    public void Refresh()

    {

        LoadFromSettings();

        RefreshActiveSection();

        NotifyLockdownChanged();

        NotifyUpdateStatusChanged();

        RefreshVisibleNavItems();

        OnPropertyChanged(nameof(CanOpenNexusConsole));

    }



    public void NotifyUpdateStatusChanged()

    {

        OnPropertyChanged(nameof(UpdateStatusSummary));

        OnPropertyChanged(nameof(CurrentVersionLabel));

        OnPropertyChanged(nameof(AboutVersionLabel));

        OnPropertyChanged(nameof(AboutBuildLabel));

        OnPropertyChanged(nameof(CanDownloadAndInstallUpdate));

        LatestVersionLabel = _updateService.LastResult?.RemoteManifest?.Version ?? "—";

        CommandManager.InvalidateRequerySuggested();

    }



    private void SelectSection(object? parameter)

    {

        if (parameter is NexusSettingsSection section)

        {

            SelectedSection = section;

            return;

        }



        if (parameter is NexusSettingsNavItem item)

        {

            SelectedSection = item.Section;

            return;

        }



        if (Enum.TryParse<NexusSettingsSection>(parameter?.ToString(), ignoreCase: true, out var parsed))

        {

            SelectedSection = parsed;

        }

    }



    private void UpdateInfoPanel()

    {

        var item = _allNavItems.FirstOrDefault(i => i.Section == SelectedSection);

        InfoPanelTitle = item?.Title ?? "Indstillinger";

        InfoPanelBody = item?.InfoHint ?? "Nexus Settings — ikke Windows Settings.";

    }



    private void RefreshActiveSection()

    {

        switch (SelectedSection)

        {

            case NexusSettingsSection.Display:

                RefreshMonitors();

                UpdateDisplayScaling();

                break;

            case NexusSettingsSection.Audio:

                RefreshAudio();

                break;

            case NexusSettingsSection.Network:

                RefreshNetwork();

                break;

            case NexusSettingsSection.Bluetooth:

                RefreshBluetooth();

                break;

            case NexusSettingsSection.Devices:

                RefreshDevices();

                break;

            case NexusSettingsSection.Printers:

                RefreshPrinters();

                break;

            case NexusSettingsSection.Updates:

            case NexusSettingsSection.About:

                NotifyUpdateStatusChanged();

                break;

            case NexusSettingsSection.Account:

                RefreshAccount();

                break;

            case NexusSettingsSection.Identity:

                RefreshIdentity();

                break;

            case NexusSettingsSection.ControlCenter:

                StartControlCenterPolling();

                RefreshControlCenter();

                break;

            case NexusSettingsSection.DefaultApps:

                LoadDefaultAppPreferences();

                break;

            case NexusSettingsSection.DeveloperDiagnostics:

                RefreshDeveloperDiagnostics();

                break;

        }

        StopControlCenterPollingIfNeeded(SelectedSection);
    }

    private void StopControlCenterPollingIfNeeded(NexusSettingsSection section)
    {
        if (section != NexusSettingsSection.ControlCenter)
        {
            StopControlCenterPolling();
        }
    }

    private void StartControlCenterPolling()
    {
        if (_controlCenterPollTimer is not null)
        {
            return;
        }

        _controlCenterPollTimer = new System.Windows.Threading.DispatcherTimer
        {
            Interval = _controlCenter.PollInterval,
        };
        _controlCenterPollTimer.Tick += (_, _) => RefreshControlCenter();
        _controlCenterPollTimer.Start();
    }

    private void StopControlCenterPolling()
    {
        if (_controlCenterPollTimer is null)
        {
            return;
        }

        _controlCenterPollTimer.Stop();
        _controlCenterPollTimer = null;
    }

    private void LoadFromSettings()

    {

        var settings = _userSettings.Current;

        SelectedTheme = settings.Theme;

        SelectedAccent = string.IsNullOrWhiteSpace(settings.AccentColor) ? "auto" : settings.AccentColor;

        AnimationIntensity = string.IsNullOrWhiteSpace(settings.AnimationIntensity) ? "normal" : settings.AnimationIntensity;

        ShellFullscreen = settings.ShellFullscreen;

        HideWindowsTaskbar = settings.HideWindowsTaskbar;

        SpanAllMonitors = settings.SpanAllMonitors;

        PerformanceMode = settings.PerformanceMode;

        ReducedMotionWhenInactive = settings.ReducedMotionWhenInactive;

        WallpaperPreview = CreateImageSource(_userSettings.ResolveWallpaperUri());

        BuildChannel = "POC";

        UpdateInfoPanel();

    }



    private void RefreshMonitors()

    {

        try

        {

            Monitors.Clear();

            foreach (var monitor in _displaySettings.GetMonitors())

            {

                Monitors.Add(new MonitorSettingsItem(monitor));

            }



            SelectedMonitor = Monitors.FirstOrDefault(static m => m.IsPrimary) ?? Monitors.FirstOrDefault();

        }

        catch (Exception ex)

        {

            StatusMessage = $"Skærme kunne ikke læses: {ex.Message}";

        }



        OnPropertyChanged(nameof(MonitorCountLabel));

    }



    private void UpdateDisplayScaling()

    {

        try

        {

            var source = PresentationSource.FromVisual(Application.Current.MainWindow);

            if (source?.CompositionTarget is not null)

            {

                var m = source.CompositionTarget.TransformToDevice;

                var scale = Math.Round(m.M11 * 100);

                DisplayScalingLabel = $"{scale:0}% (system DPI)";

                return;

            }

        }

        catch

        {

            // POC fallback

        }



        DisplayScalingLabel = "100% (system DPI)";

    }



    private void RefreshAudio()

    {

        var snapshot = _audio.Capture();

        AudioOutputDevice = snapshot.OutputDevice;

        _audioVolume = snapshot.VolumePercent;

        OnPropertyChanged(nameof(AudioVolume));

    }



    private void RefreshNetwork()

    {

        var snapshot = _networkInfo.Capture();

        ActiveNetwork = snapshot.ActiveNetwork;

        IpAddress = snapshot.IpAddress;

        SignalStrength = snapshot.SignalStrength;

    }



    private void RefreshBluetooth()

    {

        var snapshot = _bluetooth.Capture();

        BluetoothStatus = snapshot.Status;

        PairedBluetoothDevices.Clear();

        foreach (var device in snapshot.PairedDevices)

        {

            PairedBluetoothDevices.Add(device);

        }

    }



    private void RefreshDevices()

    {

        var snapshot = _deviceInfo.Capture();

        CpuName = snapshot.CpuName;

        RamLabel = snapshot.RamLabel;

        DiskLabel = snapshot.DiskLabel;

        GpuName = snapshot.GpuName;

    }



    private void RefreshPrinters()

    {

        InstalledPrinters.Clear();

        foreach (var printer in _printers.GetInstalledPrinters())

        {

            InstalledPrinters.Add(printer);

        }

    }



    private void RefreshAccount()

    {

        var profile = _profile.LoadProfile();

        if (profile is null)

        {

            AccountName = "Ikke logget ind";

            AccountRole = "—";

            AccountEmail = "—";

            AccountSession = "Ingen aktiv session";

            return;

        }



        AccountName = string.IsNullOrWhiteSpace(profile.DisplayName) ? profile.Email : profile.DisplayName;

        AccountRole = string.IsNullOrWhiteSpace(profile.Role) ? "User" : profile.Role;

        AccountEmail = string.IsNullOrWhiteSpace(profile.Email) ? "—" : profile.Email;

        AccountSession = string.IsNullOrWhiteSpace(_profile.AccessToken) ? "Offline profil" : "Aktiv Nexus-session";

    }



    private void RefreshIdentity()

    {

        var snapshot = _identity.GetSnapshot();

        IdentityUser = snapshot.User?.DisplayName ?? "—";

        IdentityOrganization = snapshot.Organization?.Name ?? snapshot.Device?.Organization ?? "—";

        IdentityDeviceId = snapshot.Device?.DeviceId ?? "—";

        IdentityStatus = snapshot.Device?.Status.ToString() ?? "Unknown";

        IdentityTrustStatus = snapshot.Trust?.Status.ToString() ?? "Unknown";

        IdentityEnrollmentDate = snapshot.Device?.EnrollmentDate?.ToLocalTime().ToString("g")

            ?? "—";

        OnPropertyChanged(nameof(PlatformLockStatusLabel));

        OnPropertyChanged(nameof(IsWindowsLocked));

    }

    private async void RefreshControlCenter()

    {

        try

        {

            var snapshot = await _controlCenter.BuildSnapshotAsync();
            var presence = await _controlCenter.FetchPresenceSummaryAsync();

            if (presence is not null)
            {
                ControlCenterPresenceSource = presence.Source;
                ControlCenterOnlineCount = presence.OnlineCount.ToString();
                ControlCenterOfflineCount = presence.OfflineCount.ToString();
                ControlCenterWarningCount = presence.WarningCount.ToString();
                ControlCenterCriticalCount = presence.CriticalCount.ToString();

                ControlCenterDevices.Clear();
                foreach (var device in presence.Devices)
                {
                    ControlCenterDevices.Add(device);
                }
            }

            if (snapshot.RemoteDashboard is not null)

            {

                var remote = snapshot.RemoteDashboard;

                ControlCenterSource = $"Remote ({remote.Source})";

                ControlCenterSummary = $"{remote.OrganizationCount} orgs · {remote.DeviceCount} enheder · {remote.PendingEnrollmentCount} afventer";

                ControlCenterPending = remote.PendingEnrollmentCount.ToString();

                if (remote.TrustSummary is not null)

                {

                    ControlCenterTrustSummary =

                        $"Trusted {remote.TrustSummary.Trusted} · Pending {remote.TrustSummary.Pending} · Blocked {remote.TrustSummary.Blocked}";

                }

                else

                {

                    ControlCenterTrustSummary = "—";

                }

                return;

            }

            ControlCenterSource = _controlCenter.IsRemoteConfigured ? "Remote utilgængelig" : "Lokal POC";

            ControlCenterSummary = snapshot.Organization is null

                ? "Ingen lokal organisation — gennemfør enrollment."

                : $"{snapshot.Organization.Name} · 1 enhed (lokal)";

            ControlCenterTrustSummary = snapshot.CurrentDevice?.TrustStatus.ToString() ?? "Unknown";

            ControlCenterPending = "0";

            if (presence is not null && presence.Source == "local")
            {
                ControlCenterPresenceSource = "local";
            }

        }

        catch (Exception ex)

        {

            ControlCenterSource = "Fejl";

            ControlCenterSummary = ex.Message;

        }

    }

    private void LockWindows()

    {

        var profile = _profile.CurrentProfile;

        var actor = profile?.Email ?? profile?.DisplayName ?? "settings";

        _platformLock.Lock(actor);

        OnPropertyChanged(nameof(PlatformLockStatusLabel));

        OnPropertyChanged(nameof(IsWindowsLocked));

        ShellSettingsChanged?.Invoke(this, EventArgs.Empty);

        StatusMessage = "Windows er låst igen.";

    }



    private async Task CheckUpdatesAsync()

    {

        IsCheckingUpdates = true;

        try

        {

            await App.Services.RefreshUpdateStatusAsync();

            NotifyUpdateStatusChanged();

            StatusMessage = UpdateStatusSummary;

        }

        catch (Exception ex)

        {

            StatusMessage = $"Opdateringstjek fejlede: {ex.Message}";

        }

        finally

        {

            IsCheckingUpdates = false;

        }

    }



    private async Task DownloadAndInstallUpdateAsync()

    {

        if (!CanDownloadAndInstallUpdate || _updateService.LastResult?.RemoteManifest is null)

        {

            return;

        }



        IsCheckingUpdates = true;

        try

        {

            var progress = new Progress<string>(_ => { });

            var download = await _updateService.DownloadUpdateAsync(

                _updateService.LastResult.RemoteManifest,

                progress);

            if (download.Status == UpdateApplyStatus.Failed)

            {

                StatusMessage = download.ErrorMessage ?? "Download fejlede";

                NotifyUpdateStatusChanged();

                return;

            }



            if (_updateService.FlowState != ClientUpdateFlowState.Ready)

            {

                StatusMessage = "Opdatering downloadet, men ikke klar til installation.";

                NotifyUpdateStatusChanged();

                return;

            }



            var manifest = _updateService.LastResult.RemoteManifest;

            var confirm = MessageBox.Show(

                $"Installér Nexus build {manifest.Build} ({manifest.Version})?\n\nShell genstarter efter installation.",

                "Bekræft opdatering",

                MessageBoxButton.YesNo,

                MessageBoxImage.Question);

            if (confirm != MessageBoxResult.Yes)

            {

                StatusMessage = "Opdatering klar — vælg Installér i Detaljer…";

                NotifyUpdateStatusChanged();

                return;

            }



            var install = await _updateService.InstallStagedUpdateAsync(progress);

            if (install.RestartScheduled)

            {

                Application.Current.Shutdown();

                return;

            }



            StatusMessage = install.ErrorMessage ?? UpdateStatusSummary;

            NotifyUpdateStatusChanged();

            App.Services.DesktopViewModel.NotifyUpdateStatus();

        }

        finally

        {

            IsCheckingUpdates = false;

        }

    }



    private void SaveSettings()

    {

        var settings = new NexusUserSettings

        {

            SettingsVersion = 2,

            Theme = SelectedTheme,

            AccentColor = SelectedAccent,

            AnimationIntensity = AnimationIntensity,

            WallpaperPath = _userSettings.Current.WallpaperPath,

            ShellFullscreen = ShellFullscreen,

            HideWindowsTaskbar = HideWindowsTaskbar,

            SpanAllMonitors = SpanAllMonitors,

            PerformanceMode = PerformanceMode,

            ReducedMotionWhenInactive = ReducedMotionWhenInactive,

        };



        _userSettings.Save(settings);

        _themeService.Apply(settings.Theme, App.Services.ProfileService, settings.AccentColor);

        AppearanceChanged?.Invoke(this, EventArgs.Empty);

        ShellSettingsChanged?.Invoke(this, EventArgs.Empty);

        SaveDefaultAppPreferences();

        StatusMessage = "Indstillinger gemt og anvendt.";

    }



    private void BrowseWallpaper()

    {

        var dialog = new NexusOpenFileDialog

        {

            Title = "Vælg skrivebordsbaggrund",

            Filter = "Billeder|*.png;*.jpg;*.jpeg;*.webp;*.bmp|Alle filer|*.*",

        };



        var owner = System.Windows.Application.Current?.MainWindow;

        if (dialog.ShowDialog(owner) != true)

        {

            return;

        }



        try

        {

            _userSettings.ImportCustomWallpaper(dialog.FileName!);

            WallpaperPreview = CreateImageSource(_userSettings.ResolveWallpaperUri());

            StatusMessage = "Ny baggrund valgt. Tryk Gem for at anvende.";

        }

        catch (Exception ex)

        {

            StatusMessage = ex.Message;

        }

    }



    private void LoadDefaultAppPreferences()

    {

        DefaultAppPreferences.Clear();

        foreach (var row in _defaultApps.GetPreferenceRows())

        {

            DefaultAppPreferences.Add(new NexusDefaultAppPreferenceRow

            {

                CategoryId = row.CategoryId,

                CategoryLabel = row.CategoryLabel,

                ExtensionsLabel = row.ExtensionsLabel,

                SelectedApp = row.SelectedApp,

            });

        }

    }



    private void SaveDefaultAppPreferences()

    {

        _defaultApps.SavePreferences(DefaultAppPreferences.ToList());

    }



    private void ResetWallpaper()

    {

        _userSettings.ResetWallpaperToDefault();

        WallpaperPreview = CreateImageSource(_userSettings.ResolveWallpaperUri());

        StatusMessage = "Standardbaggrund valgt. Tryk Gem for at anvende.";

    }



    private void ApplyDisplaySettings()

    {

        if (SelectedMonitor is null || SelectedResolution is null)

        {

            StatusMessage = "Vælg skærm og opløsning.";

            return;

        }



        if (_displaySettings.TryApplyMode(

                SelectedMonitor.DeviceName,

                SelectedResolution.Width,

                SelectedResolution.Height,

                SelectedResolution.RefreshRate,

                out var error))

        {

            StatusMessage = "Skærmindstilling anvendt.";

            RefreshMonitors();

        }

        else

        {

            StatusMessage = error ?? "Kunne ikke ændre skærmindstilling.";

        }

    }



    private static ImageSource CreateImageSource(string uri)

    {

        try

        {

            return new BitmapImage(new Uri(uri, UriKind.Absolute));

        }

        catch

        {

            return new BitmapImage(new Uri(NexusAssets.DesktopWallpaper, UriKind.Absolute));

        }

    }



    private void RefreshVisibleNavItems()

    {

        VisibleNavItems.Clear();

        foreach (var item in _allNavItems.Where(i =>
                     _policy.IsSettingsSectionAllowed(i.Section.ToString()) &&
                     (i.Section != NexusSettingsSection.DeveloperDiagnostics || ShowDeveloperDiagnosticsSection)))

        {

            VisibleNavItems.Add(item);

        }



        if (VisibleNavItems.All(i => i.Section != SelectedSection))

        {

            SelectedSection = VisibleNavItems.FirstOrDefault()?.Section ?? NexusSettingsSection.General;

        }

    }



    private void NotifyLockdownChanged()

    {

        OnPropertyChanged(nameof(LockdownStatusLabel));

        OnPropertyChanged(nameof(SafePocStatus));

        OnPropertyChanged(nameof(AuditLogPath));

        OnPropertyChanged(nameof(AllowedAppsCount));

        OnPropertyChanged(nameof(BlockedAppsCount));

        OnPropertyChanged(nameof(DeveloperConsoleStatus));

        OnPropertyChanged(nameof(AllowWindowsEscape));

        OnPropertyChanged(nameof(ShowDeveloperDiagnosticsSection));

        RefreshVisibleNavItems();

    }

    private void RefreshDeveloperDiagnostics()
    {
        var recent = _diagnostics.GetRecentEvents(8);
        DiagnosticsEventsSummary = recent.Count == 0
            ? "Ingen events endnu"
            : string.Join(" · ", recent.Select(e => $"{e.EventName}"));
        OnPropertyChanged(nameof(DiagnosticsUptimeLabel));
        OnPropertyChanged(nameof(DiagnosticsCpuLabel));
        OnPropertyChanged(nameof(DiagnosticsMemoryLabel));
        OnPropertyChanged(nameof(DiagnosticsUiLatencyLabel));
        OnPropertyChanged(nameof(DiagnosticsApiLatencyLabel));
        OnPropertyChanged(nameof(DiagnosticsActiveWindowsLabel));
        OnPropertyChanged(nameof(DiagnosticsTimersLabel));
        OnPropertyChanged(nameof(DiagnosticsSessionLabel));
    }

    private void StartDiagnosticsSession()
    {
        _diagnostics.StartSession();
        DiagnosticsStatusMessage = "Diagnostiksession startet.";
        RefreshDeveloperDiagnostics();
    }

    private void StopDiagnosticsSession()
    {
        _diagnostics.StopSession();
        DiagnosticsStatusMessage = "Diagnostiksession stoppet.";
        RefreshDeveloperDiagnostics();
    }

    private async void ExportDiagnosticsAsync()
    {
        try
        {
            var zipPath = await _diagnostics.ExportSessionZipAsync();
            DiagnosticsStatusMessage = $"Diagnostikpakke eksporteret: {zipPath}";
        }
        catch (Exception ex)
        {
            DiagnosticsStatusMessage = $"Eksport mislykkedes: {ex.Message}";
        }
    }

    private async void SendDiagnosticsAsync()
    {
        try
        {
            var result = await _diagnostics.SendDiagnosticsAsync();
            DiagnosticsStatusMessage =
                $"{result.Message} Support ID: {result.SupportId}. Zip: {result.ZipPath}";
        }
        catch (Exception ex)
        {
            DiagnosticsStatusMessage = $"Send diagnostik mislykkedes: {ex.Message}";
        }
    }

    private void CopyDiagnosticsInfo()
    {
        var info =
            $"Ninja Nexus build {_clientVersion.Build} ({_clientVersion.Version})\n" +
            $"Uptime: {DiagnosticsUptimeLabel}\n" +
            $"CPU: {DiagnosticsCpuLabel} · RAM: {DiagnosticsMemoryLabel}\n" +
            $"UI latency: {DiagnosticsUiLatencyLabel} · API: {DiagnosticsApiLatencyLabel}\n" +
            $"Aktive vinduer: {DiagnosticsActiveWindowsLabel}\n" +
            $"Aktive timers: {DiagnosticsTimersLabel}\n" +
            $"Session: {DiagnosticsSessionLabel}\n" +
            $"Events: {DiagnosticsEventsSummary}";
        Clipboard.SetText(info);
        DiagnosticsStatusMessage = "Diagnostikinfo kopieret til udklipsholder.";
    }

    private static string FormatUptime(TimeSpan uptime) =>
        uptime.TotalHours >= 1
            ? $"{(int)uptime.TotalHours}t {uptime.Minutes}m"
            : $"{uptime.Minutes}m {uptime.Seconds}s";



    private void OnPropertyChanged([CallerMemberName] string? name = null) =>

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

}



public sealed class MonitorSettingsItem

{

    public MonitorSettingsItem(DisplayMonitorInfo monitor)

    {

        DeviceName = monitor.DeviceName;

        FriendlyName = monitor.FriendlyName;

        IsPrimary = monitor.IsPrimary;

        CurrentLabel = $"{monitor.CurrentWidth} × {monitor.CurrentHeight} @ {monitor.RefreshRate} Hz";

        Modes = monitor.Modes;

    }



    public string DeviceName { get; }

    public string FriendlyName { get; }

    public bool IsPrimary { get; }

    public string CurrentLabel { get; }

    public IReadOnlyList<DisplayModeInfo> Modes { get; }



    public string DisplayLabel => IsPrimary ? $"{FriendlyName} (primær)" : FriendlyName;

}


