using Microsoft.UI.Text;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage.Pickers;
using Windows.System;
using WinRT.Interop;
using YMhut.Box.Core.App;
using YMhut.Box.Core.Startup;
using YMhut.Box.WinUI.Services;

namespace YMhut.Box.WinUI.Views;

public sealed record StartupCheckResultPayload(
    StartupCheckReport? CurrentReport,
    IReadOnlyList<StartupCheckReportSummary> HistorySummaries);

public sealed class StartupCheckResultPage : Page
{
    private const int InitialItemBatchSize = 48;
    private const int MoreItemBatchSize = 96;
    private const int RenderChunkSize = 12;

    private readonly IInstallIntegrityCheckService _integrityCheckService = AppServices.GetRequiredService<IInstallIntegrityCheckService>();
    private readonly AppPaths _paths = AppServices.GetRequiredService<AppPaths>();
    private readonly StartupCheckResultPayload? _preloadedPayload;
    private readonly Action? _goBack;
    private readonly StackPanel _historyList = new() { Spacing = 8 };
    private readonly StackPanel _itemList = new() { Spacing = 8 };
    private readonly ComboBox _filterBox = new() { MinWidth = 160 };
    private readonly TextBlock _summaryText = ModernUi.Text(T("正在加载启动自检结果。", "Loading startup check results."), 14, foreground: ModernUi.TextSecondary);
    private readonly TextBlock _selectedReportText = ModernUi.Text("", 12, foreground: ModernUi.TextSecondary, maxLines: 2);
    private readonly TextBlock _identityText = ModernUi.Text("", 12, foreground: ModernUi.TextSecondary, maxLines: 2);
    private readonly ProgressBar _itemRenderProgressBar = new()
    {
        Minimum = 0,
        Maximum = 100,
        Height = 4,
        Visibility = Visibility.Collapsed
    };
    private readonly TextBlock _itemRenderProgressText = ModernUi.Text("", 12, foreground: ModernUi.TextSecondary, maxLines: 1);

    private IReadOnlyList<StartupCheckReportSummary> _history = [];
    private IReadOnlyList<StartupCheckItem> _filteredItems = [];
    private StartupCheckReport? _currentReport;
    private Button? _loadMoreItemsButton;
    private bool _runningCheck;
    private bool _loaded;
    private bool _renderingItems;
    private int _renderedItemCount;
    private int _itemRenderVersion;

    public StartupCheckResultPage(Action? goBack = null)
        : this(null, goBack)
    {
    }

    public StartupCheckResultPage(StartupCheckResultPayload? preloadedPayload, Action? goBack = null)
    {
        _preloadedPayload = preloadedPayload;
        _goBack = goBack;
        Background = ModernUi.AppBackground;
        Content = BuildContent();
        Loaded += async (_, _) =>
        {
            if (_loaded)
            {
                return;
            }

            _loaded = true;
            await LoadAsync();
        };
    }

    private UIElement BuildContent()
    {
        _filterBox.Items.Add(new ComboBoxItem { Content = T("全部", "All"), Tag = "all" });
        _filterBox.Items.Add(new ComboBoxItem { Content = T("缺失 / 失败", "Missing / failed"), Tag = "missing" });
        _filterBox.Items.Add(new ComboBoxItem { Content = T("警告", "Warnings"), Tag = "warning" });
        _filterBox.Items.Add(new ComboBoxItem { Content = T("关键", "Critical"), Tag = "critical" });
        _filterBox.SelectedIndex = 0;
        _filterBox.SelectionChanged += (_, _) => _ = RenderItemsAsync();
        AutomationProperties.SetName(_filterBox, T("启动自检结果筛选", "Startup check result filter"));

        var body = new Grid { ColumnSpacing = 16, RowSpacing = 16 };
        body.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(320) });
        body.ColumnDefinitions.Add(new ColumnDefinition());
        var historySection = BuildHistorySection();
        var itemSection = BuildItemSection();
        body.Children.Add(historySection);
        Grid.SetColumn(itemSection, 1);
        body.Children.Add(itemSection);
        body.SizeChanged += (_, e) =>
        {
            var narrow = e.NewSize.Width < 900;
            body.ColumnDefinitions.Clear();
            body.RowDefinitions.Clear();
            body.ColumnDefinitions.Add(new ColumnDefinition());
            if (narrow)
            {
                body.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                body.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                Grid.SetColumn(historySection, 0);
                Grid.SetColumn(itemSection, 0);
                Grid.SetRow(historySection, 0);
                Grid.SetRow(itemSection, 1);
            }
            else
            {
                body.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
                body.ColumnDefinitions[0].Width = new GridLength(320);
                Grid.SetColumn(historySection, 0);
                Grid.SetColumn(itemSection, 1);
                Grid.SetRow(historySection, 0);
                Grid.SetRow(itemSection, 0);
            }
        };

        var root = new StackPanel
        {
            Padding = new Thickness(28, 24, 40, 28),
            Spacing = 16,
            Children =
            {
                BuildHeader(),
                body
            }
        };

        return new ScrollViewer
        {
            VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
            HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
            Padding = new Thickness(0, 0, 8, 0),
            Content = root
        };
    }

    private Border BuildHeader()
    {
        var back = ModernUi.IconButton("\uE72B", T("返回服务状态", "Back to service status"), () => _goBack?.Invoke());
        back.IsEnabled = _goBack is not null;
        var run = ModernUi.PillButton(T("重新自检", "Run check"), "\uE9D9", async () => await RunManualCheckAsync(), primary: true);
        var copy = ModernUi.PillButton(T("复制摘要", "Copy summary"), "\uE8C8", CopySummary);
        var export = ModernUi.PillButton(T("导出 JSON", "Export JSON"), "\uE74E", async () => await ExportJsonAsync());
        var openInstall = ModernUi.PillButton(T("安装目录", "Install root"), "\uE838", async () => await OpenInstallRootAsync());
        var openLogs = ModernUi.PillButton(T("日志", "Logs"), "\uE8A7", async () => await OpenLogDirectoryAsync());

        var actions = new VariableSizedWrapGrid
        {
            Orientation = Orientation.Horizontal,
            ItemWidth = 126,
            ItemHeight = 42,
            Children = { run, copy, export, openInstall, openLogs }
        };

        var grid = new Grid { ColumnSpacing = 14, RowSpacing = 12 };
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.ColumnDefinitions.Add(new ColumnDefinition());
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.Children.Add(back);
        var title = new StackPanel
        {
            Spacing = 5,
            Children =
            {
                ModernUi.Text(T("启动自检结果", "Startup Check Results"), 24, FontWeights.SemiBold),
                _summaryText,
                _selectedReportText,
                _identityText
            }
        };
        Grid.SetColumn(title, 1);
        grid.Children.Add(title);
        Grid.SetColumn(actions, 2);
        grid.Children.Add(actions);
        grid.SizeChanged += (_, e) =>
        {
            var narrow = e.NewSize.Width < 960;
            grid.ColumnDefinitions.Clear();
            grid.RowDefinitions.Clear();
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            if (narrow)
            {
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                Grid.SetColumn(actions, 0);
                Grid.SetColumnSpan(actions, 2);
                Grid.SetRow(actions, 1);
            }
            else
            {
                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
                Grid.SetColumn(actions, 2);
                Grid.SetColumnSpan(actions, 1);
                Grid.SetRow(actions, 0);
            }
        };

        return ModernUi.Card(grid, new Thickness(18), radius: 8);
    }

    private Border BuildHistorySection()
    {
        return ModernUi.Card(new StackPanel
        {
            Spacing = 12,
            Children =
            {
                ModernUi.Text(T("当前安装历史", "Current History"), 18, FontWeights.SemiBold),
                ModernUi.Text(T("这里只列出当前安装目录的报告；历史安装记录不会参与当前健康状态。", "Only reports from the current install root are listed here. Historical installs stay out of current health."), 12, foreground: ModernUi.TextSecondary, maxLines: 3),
                _historyList
            }
        }, new Thickness(16), radius: 8);
    }

    private Border BuildItemSection()
    {
        _loadMoreItemsButton = ModernUi.PillButton(T("加载更多", "Load more"), "\uE710", async () => await RenderNextItemBatchAsync(_itemRenderVersion, MoreItemBatchSize));
        _loadMoreItemsButton.Visibility = Visibility.Collapsed;

        var toolbar = new Grid { ColumnSpacing = 10 };
        toolbar.ColumnDefinitions.Add(new ColumnDefinition());
        toolbar.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        toolbar.Children.Add(ModernUi.Text(T("详情", "Details"), 18, FontWeights.SemiBold));
        Grid.SetColumn(_filterBox, 1);
        toolbar.Children.Add(_filterBox);

        return ModernUi.Card(new StackPanel
        {
            Spacing = 12,
            Children =
            {
                toolbar,
                _itemRenderProgressText,
                _itemRenderProgressBar,
                _itemList,
                _loadMoreItemsButton
            }
        }, new Thickness(16), radius: 8);
    }

    private async Task LoadAsync()
    {
        try
        {
            if (_preloadedPayload is not null)
            {
                _history = _preloadedPayload.HistorySummaries;
                _currentReport = _preloadedPayload.CurrentReport;
                if (_currentReport is null && _history.Count > 0)
                {
                    _summaryText.Text = T("正在读取选中的启动自检报告...", "Reading selected startup check report...");
                    _currentReport = await Task.Run(async () => await _integrityCheckService.GetReportAsync(_history[0].Id).ConfigureAwait(false));
                }

                await RenderAsync();
                return;
            }

            _summaryText.Text = T("正在读取当前安装历史...", "Reading current-install history...");
            _history = await Task.Run(async () => await _integrityCheckService.GetCurrentHistoryAsync(30).ConfigureAwait(false));
            _summaryText.Text = T("正在读取最新当前报告...", "Reading latest current report...");
            _currentReport = await Task.Run(async () => await _integrityCheckService.GetLatestCurrentReportAsync(StartupCheckKind.FastPreflight).ConfigureAwait(false));
            if (_currentReport is null && _history.Count > 0)
            {
                _currentReport = await Task.Run(async () => await _integrityCheckService.GetReportAsync(_history[0].Id).ConfigureAwait(false));
            }

            await RenderAsync();
        }
        catch (Exception exception)
        {
            CrashLog.Write(exception);
            _summaryText.Text = T($"无法加载自检历史：{FriendlyError(exception.Message)}", $"Could not load check history: {FriendlyError(exception.Message)}");
            ToastService.Show(T("无法加载启动自检结果。", "Could not load startup check results."), ToastKind.Error);
        }
    }

    private async Task RunManualCheckAsync()
    {
        if (_runningCheck)
        {
            return;
        }

        _runningCheck = true;
        _summaryText.Text = T("正在执行安装完整性检查。", "Running install integrity check.");
        try
        {
            _itemRenderProgressText.Text = T("正在检查；完成后会分批渲染详情。", "Running check; details will render in batches when complete.");
            _itemRenderProgressBar.Visibility = Visibility.Visible;
            _itemRenderProgressBar.IsIndeterminate = true;
            _currentReport = await Task.Run(async () => await _integrityCheckService.RunManualIntegrityCheckAsync().ConfigureAwait(false));
            _history = await Task.Run(async () => await _integrityCheckService.GetCurrentHistoryAsync(30).ConfigureAwait(false));
            _itemRenderProgressBar.IsIndeterminate = false;
            await RenderAsync();
            ToastService.Show(_currentReport.HasVisibleIssues
                ? T("检查完成：当前安装仍有问题。", "Check complete with current-install issues.")
                : T("检查完成：当前安装没有问题。", "Check complete with no current-install issues."),
                _currentReport.HasVisibleIssues ? ToastKind.Warning : ToastKind.Success);
        }
        catch (Exception exception)
        {
            CrashLog.Write(exception);
            _summaryText.Text = T($"检查失败：{FriendlyError(exception.Message)}", $"Check failed: {FriendlyError(exception.Message)}");
            ToastService.Show(T("安装完整性检查失败。", "Install integrity check failed."), ToastKind.Error);
        }
        finally
        {
            _runningCheck = false;
        }
    }

    private async Task RenderAsync()
    {
        RenderSummary();
        RenderHistory();
        await RenderItemsAsync();
    }

    private void RenderSummary()
    {
        if (_currentReport is null)
        {
            _summaryText.Text = T("当前安装尚未生成启动自检报告。", "No startup check report has been created for the current install yet.");
            _selectedReportText.Text = string.Empty;
            _identityText.Text = string.Empty;
            return;
        }

        _summaryText.Text = T(
            $"{KindText(_currentReport.Kind)}：{_currentReport.VisibleIssueCount} 个当前问题，关键 {_currentReport.VisibleCriticalIssueCount}，警告 {_currentReport.VisibleWarningIssueCount}。",
            $"{KindText(_currentReport.Kind)}: {_currentReport.VisibleIssueCount} current issues, {_currentReport.VisibleCriticalIssueCount} critical, {_currentReport.VisibleWarningIssueCount} warnings.");
        _selectedReportText.Text = $"{_currentReport.CompletedAt:yyyy-MM-dd HH:mm:ss} / {_currentReport.InstallRoot}";
        _identityText.Text = T($"安装身份：{_currentReport.InstallIdentity} / 检查基准：{_currentReport.CheckBasis}", $"Identity: {_currentReport.InstallIdentity} / Basis: {_currentReport.CheckBasis}");
    }

    private void RenderHistory()
    {
        _historyList.Children.Clear();
        if (_history.Count == 0)
        {
            _historyList.Children.Add(ModernUi.Card(ModernUi.Text(T("暂无当前安装历史。", "No current-install history yet."), 13, foreground: ModernUi.TextSecondary), new Thickness(12), radius: 8, background: ModernUi.SurfaceAlt));
            return;
        }

        foreach (var report in _history.OrderByDescending(report => report.CompletedAt))
        {
            _historyList.Children.Add(BuildHistoryRow(report));
        }
    }

    private async Task RenderItemsAsync()
    {
        var renderVersion = Interlocked.Increment(ref _itemRenderVersion);
        _renderedItemCount = 0;
        _itemList.Children.Clear();
        if (_currentReport is null)
        {
            _filteredItems = [];
            UpdateItemRenderProgress(0, 0, loading: false);
            _itemList.Children.Add(ModernUi.Card(ModernUi.Text(T("暂无可显示的检查详情。", "No check details to show."), 13, foreground: ModernUi.TextSecondary), new Thickness(12), radius: 8, background: ModernUi.SurfaceAlt));
            return;
        }

        var tag = ((_filterBox.SelectedItem as ComboBoxItem)?.Tag as string) ?? "all";
        _filteredItems = _currentReport.Items.Where(item => tag switch
        {
            "missing" => item.IsIssue,
            "warning" => item.IsIssue && item.Severity == StartupCheckSeverity.Warning,
            "critical" => item.IsIssue && item.Severity == StartupCheckSeverity.Critical,
            _ => true
        }).ToArray();

        if (_filteredItems.Count == 0)
        {
            UpdateItemRenderProgress(0, 0, loading: false);
            _itemList.Children.Add(ModernUi.Card(ModernUi.Text(T("没有项目符合当前筛选。", "No items match the current filter."), 13, foreground: ModernUi.TextSecondary), new Thickness(12), radius: 8, background: ModernUi.SurfaceAlt));
            return;
        }

        await RenderNextItemBatchAsync(renderVersion, InitialItemBatchSize);
    }

    private async Task RenderNextItemBatchAsync(int renderVersion, int count)
    {
        if (_filteredItems.Count == 0 || renderVersion != _itemRenderVersion)
        {
            return;
        }

        if (_renderingItems)
        {
            await Task.Delay(40);
            if (renderVersion == _itemRenderVersion)
            {
                await RenderNextItemBatchAsync(renderVersion, count);
            }

            return;
        }

        _renderingItems = true;
        SetLoadMoreEnabled(false);
        try
        {
            var target = Math.Min(_filteredItems.Count, _renderedItemCount + Math.Max(1, count));
            while (_renderedItemCount < target)
            {
                if (renderVersion != _itemRenderVersion)
                {
                    return;
                }

                var chunkEnd = Math.Min(target, _renderedItemCount + RenderChunkSize);
                for (; _renderedItemCount < chunkEnd; _renderedItemCount++)
                {
                    _itemList.Children.Add(BuildItemRow(_filteredItems[_renderedItemCount]));
                }

                UpdateItemRenderProgress(_renderedItemCount, _filteredItems.Count, loading: _renderedItemCount < target);
                await Task.Yield();
            }

            UpdateItemRenderProgress(_renderedItemCount, _filteredItems.Count, loading: false);
        }
        finally
        {
            _renderingItems = false;
            SetLoadMoreEnabled(_renderedItemCount < _filteredItems.Count);
        }
    }

    private void UpdateItemRenderProgress(int rendered, int total, bool loading)
    {
        if (total <= 0)
        {
            _itemRenderProgressBar.Visibility = Visibility.Collapsed;
            _itemRenderProgressBar.IsIndeterminate = false;
            _itemRenderProgressText.Text = string.Empty;
            SetLoadMoreEnabled(false);
            return;
        }

        _itemRenderProgressBar.Visibility = Visibility.Visible;
        _itemRenderProgressBar.IsIndeterminate = false;
        _itemRenderProgressBar.Value = Math.Clamp(rendered / (double)total * 100, 0, 100);
        _itemRenderProgressText.Text = loading
            ? T($"正在渲染详情：{rendered}/{total}", $"Rendering details: {rendered}/{total}")
            : rendered < total
                ? T($"已显示 {rendered}/{total} 项。加载更多可继续查看。", $"{rendered}/{total} items shown. Load more to continue.")
                : T($"已显示全部 {total} 项。", $"All {total} items shown.");
    }

    private void SetLoadMoreEnabled(bool enabled)
    {
        if (_loadMoreItemsButton is null)
        {
            return;
        }

        _loadMoreItemsButton.Visibility = enabled ? Visibility.Visible : Visibility.Collapsed;
        _loadMoreItemsButton.IsEnabled = enabled;
    }

    private Border BuildHistoryRow(StartupCheckReportSummary report)
    {
        var button = ModernUi.PillButton(T("查看", "Use"), "\uE8A7", () =>
        {
            _ = LoadHistoryReportAsync(report);
        });
        var grid = new Grid { ColumnSpacing = 10 };
        grid.ColumnDefinitions.Add(new ColumnDefinition());
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.Children.Add(new StackPanel
        {
            Spacing = 3,
            Children =
            {
                ModernUi.Text(KindText(report.Kind), 14, FontWeights.SemiBold, maxLines: 1),
                ModernUi.Text(T($"{report.CompletedAt:yyyy-MM-dd HH:mm} / 当前问题 {report.VisibleIssueCount} 个", $"{report.CompletedAt:yyyy-MM-dd HH:mm} / {report.VisibleIssueCount} current issues"), 12, foreground: ModernUi.TextSecondary, maxLines: 1),
                new StackPanel
                {
                    Orientation = Orientation.Horizontal,
                    Spacing = 6,
                    Children =
                    {
                        ModernUi.SmallBadge(report.HasVisibleIssues ? T("有当前问题", "Current issues") : T("健康", "Healthy"), report.HasVisibleIssues ? ModernUi.Bronze : ModernUi.Accent, ModernUi.Surface),
                        ModernUi.SmallBadge(report.IsCurrentInstall ? T("当前安装", "Current") : T("历史安装", "Historical"), report.IsCurrentInstall ? ModernUi.Accent : ModernUi.TextSecondary, ModernUi.Surface)
                    }
                }
            }
        });
        Grid.SetColumn(button, 1);
        grid.Children.Add(button);
        return ModernUi.Card(grid, new Thickness(12), radius: 8, background: IsSelected(report) ? ModernUi.AccentSoft : ModernUi.SurfaceAlt);
    }

    private async Task LoadHistoryReportAsync(StartupCheckReportSummary summary)
    {
        if (_currentReport is not null && _currentReport.Id == summary.Id)
        {
            await RenderAsync();
            return;
        }

        _summaryText.Text = T("正在读取选中的启动自检报告...", "Reading selected startup check report...");
        _itemRenderProgressText.Text = T("正在加载详情；随后会分批渲染。", "Loading details; they will render in batches.");
        _itemRenderProgressBar.Visibility = Visibility.Visible;
        _itemRenderProgressBar.IsIndeterminate = true;
        try
        {
            _currentReport = await Task.Run(async () => await _integrityCheckService.GetReportAsync(summary.Id).ConfigureAwait(false));
            await RenderAsync();
        }
        catch (Exception exception)
        {
            CrashLog.Write(exception);
            _summaryText.Text = T($"无法加载自检报告：{FriendlyError(exception.Message)}", $"Could not load check report: {FriendlyError(exception.Message)}");
            ToastService.Show(T("无法加载选中的启动自检报告。", "Could not load the selected startup check report."), ToastKind.Error);
        }
        finally
        {
            _itemRenderProgressBar.IsIndeterminate = false;
        }
    }

    private async Task RecheckItemAsync(StartupCheckItem item)
    {
        if (_currentReport is null)
        {
            return;
        }

        try
        {
            var updated = await Task.Run(async () => await _integrityCheckService.RecheckItemAsync(_currentReport.Id, item.Id).ConfigureAwait(false));
            if (updated is null)
            {
                return;
            }

            _currentReport = _currentReport with
            {
                Items = _currentReport.Items
                    .Select(candidate => string.Equals(candidate.Id, item.Id, StringComparison.OrdinalIgnoreCase) ? updated : candidate)
                    .ToArray()
            };

            RenderSummary();
            await RenderItemsAsync();
            ToastService.Show(updated.Status == StartupCheckStatus.Passed
                ? T("当前复核已通过，旧记录仅供参考。", "Current check passed. Old record kept for reference.")
                : T("当前复核仍发现问题。", "Current check still reports an issue."),
                updated.Status == StartupCheckStatus.Passed ? ToastKind.Success : ToastKind.Warning);
        }
        catch (Exception exception)
        {
            CrashLog.Write(exception);
            ToastService.Show(T($"复核失败：{FriendlyError(exception.Message)}", $"Recheck failed: {FriendlyError(exception.Message)}"), ToastKind.Error);
        }
    }

    private Border BuildItemRow(StartupCheckItem item)
    {
        var brush = ItemBrush(item);
        var grid = new Grid
        {
            ColumnSpacing = 12,
            Padding = new Thickness(2)
        };
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.ColumnDefinitions.Add(new ColumnDefinition());
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.Children.Add(new Border
        {
            Width = 10,
            Height = 10,
            CornerRadius = new CornerRadius(5),
            Background = brush,
            VerticalAlignment = VerticalAlignment.Center
        });

        var text = new StackPanel
        {
            Spacing = 3,
            Children =
            {
                ModernUi.Text(item.Name, 14, FontWeights.SemiBold, maxLines: 1),
                ModernUi.Text(item.Status == StartupCheckStatus.Passed && item.Id.StartsWith("repaired:", StringComparison.OrdinalIgnoreCase)
                    ? T("当前复核已通过，旧记录仅供参考。", "Current check passed. Old record kept for reference.")
                    : item.Detail, 12, foreground: ModernUi.TextSecondary, maxLines: 2)
            }
        };
        if (!string.IsNullOrWhiteSpace(item.Path))
        {
            text.Children.Add(ModernUi.Text(item.Path, 11.5, foreground: ModernUi.TextSecondary, maxLines: 1));
        }

        Grid.SetColumn(text, 1);
        grid.Children.Add(text);

        var badges = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            Spacing = 6,
            Children =
            {
                ModernUi.SmallBadge(StatusText(item.Status), brush, ModernUi.Surface),
                ModernUi.SmallBadge(SeverityText(item.Severity), item.Severity == StartupCheckSeverity.Critical ? ModernUi.Danger : item.Severity == StartupCheckSeverity.Warning ? ModernUi.Bronze : ModernUi.TextSecondary, ModernUi.Surface)
            }
        };
        if (item.IsIssue && _currentReport is not null)
        {
            badges.Children.Add(ModernUi.PillButton(T("复核", "Recheck"), "\uE72C", async () => await RecheckItemAsync(item)));
        }

        Grid.SetColumn(badges, 2);
        grid.Children.Add(badges);

        return ModernUi.Card(grid, new Thickness(10), radius: 8, background: ModernUi.SurfaceAlt);
    }

    private void CopySummary()
    {
        if (_currentReport is null)
        {
            return;
        }

        var data = new DataPackage();
        data.SetText(BuildSummaryText(_currentReport));
        Clipboard.SetContent(data);
        ToastService.Show(T("启动自检摘要已复制。", "Startup check summary copied."), ToastKind.Success);
    }

    private async Task ExportJsonAsync()
    {
        if (_currentReport is null || App.CurrentWindow is null)
        {
            return;
        }

        var picker = new FileSavePicker
        {
            SuggestedFileName = $"startup-check-{_currentReport.CompletedAt:yyyyMMdd-HHmmss}"
        };
        picker.FileTypeChoices.Add("JSON", [".json"]);
        InitializeWithWindow.Initialize(picker, WindowNative.GetWindowHandle(App.CurrentWindow));
        var file = await picker.PickSaveFileAsync();
        if (file is null)
        {
            return;
        }

        await File.WriteAllTextAsync(file.Path, _currentReport.ToJson());
        ToastService.Show(T("启动自检 JSON 已导出。", "Startup check JSON exported."), ToastKind.Success);
    }

    private async Task OpenInstallRootAsync()
    {
        var root = _currentReport?.InstallRoot;
        if (!string.IsNullOrWhiteSpace(root) && Directory.Exists(root))
        {
            await Launcher.LaunchFolderPathAsync(root);
        }
    }

    private async Task OpenLogDirectoryAsync()
    {
        Directory.CreateDirectory(_paths.Logs);
        await Launcher.LaunchFolderPathAsync(_paths.Logs);
    }

    private bool IsSelected(StartupCheckReportSummary report)
        => _currentReport is not null && report.Id == _currentReport.Id;

    private static string BuildSummaryText(StartupCheckReport report)
    {
        var lines = new List<string>
        {
            T($"类型：{KindText(report.Kind)}", $"Kind: {KindText(report.Kind)}"),
            T($"完成时间：{report.CompletedAt:O}", $"Completed: {report.CompletedAt:O}"),
            T($"安装目录：{report.InstallRoot}", $"Install root: {report.InstallRoot}"),
            T($"安装身份：{report.InstallIdentity}", $"Install identity: {report.InstallIdentity}"),
            T($"清单身份：{report.ManifestIdentity}", $"Manifest identity: {report.ManifestIdentity}"),
            T($"检查基准：{report.CheckBasis}", $"Basis: {report.CheckBasis}"),
            T($"项目数：{report.Items.Count}", $"Items: {report.Items.Count}"),
            T($"当前可见问题：{report.VisibleIssueCount}", $"Visible issues: {report.VisibleIssueCount}"),
            T($"当前关键问题：{report.VisibleCriticalIssueCount}", $"Visible critical: {report.VisibleCriticalIssueCount}"),
            T($"当前警告：{report.VisibleWarningIssueCount}", $"Visible warnings: {report.VisibleWarningIssueCount}")
        };
        lines.AddRange(report.Items
            .Where(item => item.IsIssue)
            .Select(item => $"{SeverityText(item.Severity)} | {StatusText(item.Status)} | {item.Name} | {item.Detail} | {item.Path}"));
        return string.Join(Environment.NewLine, lines);
    }

    private static string FriendlyError(string? message)
        => AppLocalizer.SanitizeSensitiveText(message, 180);

    private static Brush ItemBrush(StartupCheckItem item)
    {
        if (!item.IsIssue)
        {
            return ModernUi.Accent;
        }

        return item.Severity == StartupCheckSeverity.Critical ? ModernUi.Danger : ModernUi.Bronze;
    }

    private static string KindText(StartupCheckKind kind)
    {
        return kind switch
        {
            StartupCheckKind.FastPreflight => T("快速预检", "Fast preflight"),
            StartupCheckKind.MonthlyIntegrity => T("月度完整性检查", "Monthly integrity check"),
            StartupCheckKind.ManualIntegrity => T("手动完整性检查", "Manual integrity check"),
            _ => kind.ToString()
        };
    }

    private static string StatusText(StartupCheckStatus status)
    {
        return status switch
        {
            StartupCheckStatus.Passed => T("通过", "Passed"),
            StartupCheckStatus.Missing => T("缺失", "Missing"),
            StartupCheckStatus.Failed => T("失败", "Failed"),
            StartupCheckStatus.Skipped => T("跳过", "Skipped"),
            _ => status.ToString()
        };
    }

    private static string SeverityText(StartupCheckSeverity severity)
    {
        return severity switch
        {
            StartupCheckSeverity.Critical => T("关键", "Critical"),
            StartupCheckSeverity.Warning => T("警告", "Warning"),
            StartupCheckSeverity.Info => T("信息", "Info"),
            _ => severity.ToString()
        };
    }

    private static string T(string zh, string en) => AppLocalizer.T(zh, en);
}
