using Microsoft.UI.Text;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using YMhut.Box.Core.App;
using YMhut.Box.Core.Logging;
using YMhut.Box.WinUI.Services;

namespace YMhut.Box.WinUI.Views;

public sealed class SafeBrowserLauncherPage : Page
{
    private readonly ILogService _logService = AppServices.GetRequiredService<ILogService>();
    private readonly AppPaths _paths = AppServices.GetRequiredService<AppPaths>();
    private readonly IIndependentWindowHostLauncher _windowHostLauncher = AppServices.GetRequiredService<IIndependentWindowHostLauncher>();
    private readonly TextBlock _stateText = ModernUi.Text(AppLocalizer.T("准备打开独立安全浏览器窗口。", "Ready to open the standalone safe browser window."), 14, foreground: ModernUi.TextSecondary);
    private bool _opened;

    public SafeBrowserLauncherPage()
    {
        Background = ModernUi.AppBackground;
        Content = BuildContent();
        Loaded += (_, _) => OpenBrowserWindow(auto: true);
    }

    private UIElement BuildContent()
    {
        var openButton = ModernUi.PillButton(AppLocalizer.T("打开新的安全浏览器窗口", "Open a new safe browser window"), "\uE8A7", () => OpenBrowserWindow(auto: false), primary: true);

        var card = ModernUi.Card(new StackPanel
        {
            Spacing = 16,
            Children =
            {
                ModernUi.IconTile("\uE774", 56, ModernUi.AccentSoft, ModernUi.Accent, 24),
                ModernUi.Text(AppLocalizer.T("安全浏览器", "Safe Browser"), 24, FontWeights.SemiBold),
                ModernUi.Text(AppLocalizer.T("浏览器会在独立子窗口中运行，使用临时 WebView2 用户数据目录。主窗口会记录访问目标摘要，关闭子窗口后自动清理会话数据。", "The browser runs in a standalone child window with a temporary WebView2 user data folder. The main window records a sanitized visit summary and cleans session data after the child window closes."), 14, foreground: ModernUi.TextSecondary, maxLines: 3),
                _stateText,
                openButton
            }
        }, new Thickness(24), radius: 8);

        return new Grid
        {
            Padding = new Thickness(0, 0, 24, 0),
            Children = { card }
        };
    }

    private async void OpenBrowserWindow(bool auto)
    {
        if (auto && _opened)
        {
            return;
        }

        _opened = true;
        await _windowHostLauncher.LaunchAsync(IndependentWindowHostOptions.Browser(
            AppLocalizer.T("安全浏览器", "Safe Browser"),
            SafeBrowserPage.HomeUrl,
            _paths));
        _stateText.Text = AppLocalizer.T($"安全浏览器窗口已打开：{DateTime.Now:HH:mm:ss}", $"Safe browser window opened: {DateTime.Now:HH:mm:ss}");
        ToastService.Show(AppLocalizer.T("安全浏览器窗口已打开", "Safe browser window opened"), ToastKind.Success);
        _ = _logService.WriteAsync("Information", "safe_browser", auto ? "自动打开安全浏览器子窗口" : "手动打开安全浏览器子窗口");
    }
}
