using System.Runtime.InteropServices;
using System.Text.Json;
using Microsoft.UI;
using Microsoft.UI.Text;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Microsoft.Web.WebView2.Core;
using Windows.Graphics;
using Windows.UI.ViewManagement;
using WinRT.Interop;
using YMhut.Box.Core.Settings;
using YMhut.Box.Core.Startup;
using YMhut.Box.WinUI.Services;

namespace YMhut.Box.WinUI;

public sealed class StartupSplashWindow : Window
{
    private const double WindowWidthDip = 560;
    private const double WindowHeightDip = 300;
    private const double WindowCornerRadiusDip = 22;
    private const double WindowClipRadiusDip = 24;
    private const string SplashHostName = "startup-splash.ymhut.local";

    private readonly WebView2EnvironmentFactory _webViewEnvironmentFactory = AppServices.GetRequiredService<WebView2EnvironmentFactory>();
    private readonly ISettingsService _settingsService = AppServices.GetRequiredService<ISettingsService>();
    private readonly WebView2 _webView = new()
    {
        Visibility = Visibility.Collapsed,
        HorizontalAlignment = HorizontalAlignment.Stretch,
        VerticalAlignment = VerticalAlignment.Stretch
    };
    private readonly ProgressBar _progressBar = new()
    {
        Minimum = 0,
        Maximum = 100,
        Height = 6
    };
    private readonly TextBlock _statusText = ModernUi.Text(
        AppLocalizer.T("正在初始化启动自检...", "Initializing startup check..."),
        14,
        foreground: ModernUi.TextSecondary,
        maxLines: 2);
    private readonly TextBlock _stageText = ModernUi.Text(
        AppLocalizer.T("启动自检", "Startup check"),
        13,
        foreground: ModernUi.TextSecondary,
        maxLines: 1);
    private readonly TextBlock _percentText = ModernUi.Text("0%", 14, FontWeights.SemiBold, ModernUi.Accent, maxLines: 1);
    private readonly TextBlock _resultText = ModernUi.Text(
        AppLocalizer.T("启动页只显示进度；详细结果会写入启动自检结果页。", "The startup page only shows progress; details are written to the startup check results page."),
        12,
        foreground: ModernUi.TextSecondary,
        maxLines: 2);
    private readonly Border _stateDot = new()
    {
        Width = 10,
        Height = 10,
        CornerRadius = new CornerRadius(5),
        Background = ModernUi.Info,
        VerticalAlignment = VerticalAlignment.Center
    };

    private Grid? _root;
    private UIElement? _fallbackContent;
    private Button? _forceCloseButton;
    private StartupSplashMessage? _pendingMessage;
    private IntPtr _hwnd;
    private int _roundedClipRefreshToken;
    private bool _webReady;
    private bool _webInitializationStarted;
    private bool _webSplashActive;
    private bool _nativeFallbackActive;
    private bool _fallbackCloseButtonShown;

    public StartupSplashWindow(string? theme)
    {
        var dark = ShouldUseDarkPalette(theme);
        ModernUi.SetPalette(dark);
        Title = AppLocalizer.T("YMhut Box 启动自检", "YMhut Box Startup Check");
        WindowIconService.ApplyAppIcon(this);
        Content = BuildContent(ResolveElementTheme(theme));
        ThemeService.ApplyWindowBackdrop(this, "solid");
        ConfigureWindow();
        Activated += (_, _) => ScheduleRoundedClipRefresh();
    }

    public void ReportProgress(StartupInitializationProgress progress)
    {
        if (DispatcherQueue.HasThreadAccess)
        {
            ApplyProgress(progress);
            return;
        }

        _ = DispatcherQueue.TryEnqueue(() => ApplyProgress(progress));
    }

    public void ReportOutcome(StartupInitializationSnapshot snapshot)
    {
        if (DispatcherQueue.HasThreadAccess)
        {
            ApplyOutcome(snapshot);
            return;
        }

        _ = DispatcherQueue.TryEnqueue(() => ApplyOutcome(snapshot));
    }

    public void ReportFatal(Exception exception)
    {
        if (DispatcherQueue.HasThreadAccess)
        {
            ApplyFatal(exception);
            return;
        }

        _ = DispatcherQueue.TryEnqueue(() => ApplyFatal(exception));
    }

    public void ScheduleCloseFallback(TimeSpan delay)
    {
        _ = Task.Run(async () =>
        {
            await Task.Delay(delay).ConfigureAwait(false);
            _ = DispatcherQueue.TryEnqueue(() =>
            {
                ShowFallbackCloseButton();
                PostMessage(new StartupSplashMessage(
                    "showClose",
                    AppLocalizer.T("可以关闭启动页。", "You can close the startup page."),
                    100,
                    Theme: WebTheme(_settingsService.Current.Theme),
                    ReducedMotion: !_settingsService.Current.AnimationsEnabled));
            });
        });
    }

    private UIElement BuildContent(ElementTheme theme)
    {
        _progressBar.Value = 0;
        _progressBar.Foreground = ModernUi.Accent;
        AutomationProperties.SetName(_progressBar, AppLocalizer.T("启动自检进度", "Startup check progress"));

        _fallbackContent = BuildFallbackContent(theme);
        _fallbackContent.Visibility = Visibility.Collapsed;
        _root = new Grid
        {
            RequestedTheme = theme,
            Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent),
            Children =
            {
                _webView,
                _fallbackContent
            }
        };
        _root.Loaded += async (_, _) =>
        {
            ScheduleRoundedClipRefresh();
            ScheduleNativeFallbackIfWebNotReady(TimeSpan.FromMilliseconds(900));
            await InitializeWebSplashAsync();
        };
        _root.SizeChanged += (_, _) => ScheduleRoundedClipRefresh();

        return new Border
        {
            RequestedTheme = theme,
            CornerRadius = new CornerRadius(WindowCornerRadiusDip),
            Background = ModernUi.Surface,
            Child = _root
        };
    }

    private UIElement BuildFallbackContent(ElementTheme theme)
    {
        var logo = new Border
        {
            Width = 64,
            Height = 64,
            CornerRadius = new CornerRadius(12),
            Background = ModernUi.AccentSoft,
            BorderBrush = ModernUi.Stroke,
            BorderThickness = new Thickness(1),
            Child = new Image
            {
                Source = new BitmapImage(new Uri("ms-appx:///Assets/icons/app_icon.png")),
                Width = 38,
                Height = 38,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center
            }
        };

        var title = new StackPanel
        {
            Spacing = 5,
            VerticalAlignment = VerticalAlignment.Center,
            Children =
            {
                ModernUi.Text("YMhut Box", 26, FontWeights.SemiBold, ModernUi.TextPrimary, maxLines: 1),
                _stageText
            }
        };

        var header = new Grid { ColumnSpacing = 16 };
        header.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        header.ColumnDefinitions.Add(new ColumnDefinition());
        header.Children.Add(logo);
        Grid.SetColumn(title, 1);
        header.Children.Add(title);

        var progressHeader = new Grid { ColumnSpacing = 12 };
        progressHeader.ColumnDefinitions.Add(new ColumnDefinition());
        progressHeader.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        progressHeader.Children.Add(new StackPanel
        {
            Orientation = Orientation.Horizontal,
            Spacing = 8,
            Children =
            {
                _stateDot,
                _statusText
            }
        });
        Grid.SetColumn(_percentText, 1);
        progressHeader.Children.Add(_percentText);

        _forceCloseButton = new Button
        {
            Content = AppLocalizer.T("关闭启动页", "Close startup page"),
            HorizontalAlignment = HorizontalAlignment.Right,
            Visibility = Visibility.Collapsed,
            MinHeight = 34,
            Padding = new Thickness(14, 6, 14, 6)
        };
        _forceCloseButton.Click += (_, _) => CloseOrExit();
        AutomationProperties.SetName(_forceCloseButton, AppLocalizer.T("关闭启动页", "Close startup page"));

        return new Border
        {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            VerticalAlignment = VerticalAlignment.Stretch,
            CornerRadius = new CornerRadius(22),
            Padding = new Thickness(24),
            Background = ModernUi.Surface,
            BorderBrush = ModernUi.Stroke,
            BorderThickness = new Thickness(1),
            Child = new StackPanel
            {
                Spacing = 20,
                Children =
                {
                    header,
                    new StackPanel
                    {
                        Spacing = 10,
                        Children =
                        {
                            progressHeader,
                            _progressBar,
                            _resultText,
                            _forceCloseButton
                        }
                    }
                }
            }
        };
    }

    private async Task InitializeWebSplashAsync()
    {
        if (_webInitializationStarted)
        {
            return;
        }

        _webInitializationStarted = true;
        try
        {
            var resourceFolder = Path.Combine(AppContext.BaseDirectory, "Assets", "startup-splash");
            if (!Directory.Exists(resourceFolder))
            {
                ActivateNativeFallback();
                return;
            }

            var environment = await _webViewEnvironmentFactory.CreateAsync("StartupSplash").ConfigureAwait(true);
            await _webView.EnsureCoreWebView2Async(environment);
            _webView.DefaultBackgroundColor = Windows.UI.Color.FromArgb(0, 0, 0, 0);
            _webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
            _webView.CoreWebView2.Settings.AreDevToolsEnabled = false;
            _webView.CoreWebView2.Settings.AreHostObjectsAllowed = false;
            _webView.CoreWebView2.Settings.IsStatusBarEnabled = false;
            _webView.CoreWebView2.Settings.IsZoomControlEnabled = false;
            _webView.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived;
            _webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
                SplashHostName,
                resourceFolder,
                CoreWebView2HostResourceAccessKind.Allow);
            _webView.Source = new Uri($"https://{SplashHostName}/index.html");
        }
        catch (Exception exception)
        {
            CrashLog.Write(exception);
            ActivateNativeFallback();
        }
    }

    private void ScheduleNativeFallbackIfWebNotReady(TimeSpan delay)
    {
        _ = Task.Run(async () =>
        {
            await Task.Delay(delay).ConfigureAwait(false);
            _ = DispatcherQueue.TryEnqueue(() =>
            {
                if (!_webReady && !_webSplashActive)
                {
                    ActivateNativeFallback();
                }
            });
        });
    }

    private void WebView_WebMessageReceived(CoreWebView2 sender, CoreWebView2WebMessageReceivedEventArgs args)
    {
        try
        {
            using var document = JsonDocument.Parse(args.WebMessageAsJson);
            if (!document.RootElement.TryGetProperty("type", out var type))
            {
                return;
            }

            var messageType = type.GetString();
            if (string.Equals(messageType, "ready", StringComparison.OrdinalIgnoreCase))
            {
                _webReady = true;
                if (_nativeFallbackActive)
                {
                    PostMessage(_pendingMessage ?? CreateThemeMessage());
                    return;
                }

                _webSplashActive = true;
                _webView.Visibility = Visibility.Visible;
                if (_fallbackContent is not null)
                {
                    _fallbackContent.Visibility = Visibility.Collapsed;
                }

                PostMessage(_pendingMessage ?? CreateThemeMessage());
            }
            else if (string.Equals(messageType, "closeRequested", StringComparison.OrdinalIgnoreCase))
            {
                CloseOrExit();
            }
        }
        catch
        {
        }
    }

    private void ActivateNativeFallback()
    {
        if (_webSplashActive || _nativeFallbackActive)
        {
            return;
        }

        _nativeFallbackActive = true;
        _webView.Visibility = Visibility.Collapsed;
        if (_fallbackContent is not null)
        {
            _fallbackContent.Visibility = Visibility.Visible;
        }
    }

    private void ApplyProgress(StartupInitializationProgress progress)
    {
        if (!string.IsNullOrWhiteSpace(progress.Theme))
        {
            ApplyTheme(progress.Theme);
        }

        _progressBar.IsIndeterminate = progress.IsIndeterminate;
        if (!progress.IsIndeterminate)
        {
            _progressBar.Value = Math.Clamp(progress.Progress, 0, 100);
        }

        _stageText.Text = string.IsNullOrWhiteSpace(progress.StageName)
            ? AppLocalizer.T("启动自检", "Startup check")
            : progress.StageName;
        _statusText.Text = progress.Status;
        _statusText.Foreground = progress.Severity == StartupCheckSeverity.Critical
            ? ModernUi.Danger
            : progress.Severity == StartupCheckSeverity.Warning
                ? ModernUi.Bronze
                : ModernUi.TextSecondary;
        _stateDot.Background = progress.Severity == StartupCheckSeverity.Critical
            ? ModernUi.Danger
            : progress.Severity == StartupCheckSeverity.Warning
                ? ModernUi.Bronze
                : ModernUi.Accent;
        _percentText.Text = progress.IsIndeterminate
            ? AppLocalizer.T("处理中", "Working")
            : $"{Math.Clamp(progress.Progress, 0, 100):0}%";

        var detail = progress.Detail;
        if (string.IsNullOrWhiteSpace(detail) && progress.StepCount > 0)
        {
            detail = $"{progress.StepIndex}/{progress.StepCount}";
        }

        PostMessage(new StartupSplashMessage(
            "progress",
            progress.Status,
            Math.Clamp(progress.Progress, 0, 100),
            progress.StageId,
            progress.StageName,
            progress.StepIndex,
            progress.StepCount,
            detail,
            SeverityText(progress.Severity),
            progress.IsRepairStep,
            progress.IsIndeterminate,
            Theme: WebTheme(progress.Theme ?? _settingsService.Current.Theme),
            ReducedMotion: !_settingsService.Current.AnimationsEnabled));
    }

    private void ApplyOutcome(StartupInitializationSnapshot snapshot)
    {
        var hasIssues = snapshot.HasVisibleStartupIssue;
        var status = hasIssues
            ? AppLocalizer.T("启动自检完成：发现问题。", "Startup check complete: issues found.")
            : AppLocalizer.T("启动自检完成：未发现问题。", "Startup check complete: no issues found.");
        ReportProgress(new StartupInitializationProgress(
            status,
            100,
            false,
            _settingsService.Current.Theme,
            "complete",
            AppLocalizer.T("启动自检完成", "Startup check complete"),
            10,
            10,
            status,
            hasIssues ? StartupCheckSeverity.Warning : StartupCheckSeverity.Info));

        _stateDot.Background = hasIssues ? ModernUi.Bronze : ModernUi.Accent;
        _resultText.Foreground = hasIssues ? ModernUi.Bronze : ModernUi.Accent;
        _resultText.Text = hasIssues
            ? AppLocalizer.T("发现问题。主窗口只显示状态，具体缺失项请在启动自检结果页查看。", "Issues were found. The main window only shows status; view the results page for details.")
            : AppLocalizer.T("未发现问题。可在启动自检结果页查看本次记录。", "No issues found. You can review this run on the startup check results page.");

        var durationMs = Math.Max(0, (long)(snapshot.CompletedAt - snapshot.StartedAt).TotalMilliseconds);
        PostMessage(new StartupSplashMessage(
            "complete",
            status,
            100,
            "complete",
            AppLocalizer.T("启动自检完成", "Startup check complete"),
            10,
            10,
            _resultText.Text,
            hasIssues ? "warning" : "info",
            HasIssues: hasIssues,
            VisibleIssueCount: snapshot.FastPreflightReport.VisibleIssueCount,
            DurationMs: durationMs,
            Theme: WebTheme(_settingsService.Current.Theme),
            ReducedMotion: !_settingsService.Current.AnimationsEnabled));
    }

    private void ApplyFatal(Exception exception)
    {
        var safeMessage = AppLocalizer.SanitizeSensitiveText(exception.Message, 160);
        _stateDot.Background = ModernUi.Danger;
        _progressBar.IsIndeterminate = false;
        _progressBar.Value = 100;
        _statusText.Text = AppLocalizer.T("启动初始化失败", "Startup initialization failed");
        _statusText.Foreground = ModernUi.Danger;
        _percentText.Text = AppLocalizer.T("失败", "Failed");
        _percentText.Foreground = ModernUi.Danger;
        _resultText.Text = AppLocalizer.T($"启动阶段遇到错误：{safeMessage}", $"Startup error: {safeMessage}");
        _resultText.Foreground = ModernUi.Danger;
        ShowFallbackCloseButton();
        PostMessage(new StartupSplashMessage(
            "fatal",
            _statusText.Text,
            100,
            "fatal",
            AppLocalizer.T("启动失败", "Startup failed"),
            Detail: _resultText.Text,
            Severity: "critical",
            Theme: WebTheme(_settingsService.Current.Theme),
            ReducedMotion: !_settingsService.Current.AnimationsEnabled));
    }

    private void ShowFallbackCloseButton()
    {
        if (_fallbackCloseButtonShown || _forceCloseButton is null)
        {
            return;
        }

        if (!_webSplashActive)
        {
            ActivateNativeFallback();
        }

        _fallbackCloseButtonShown = true;
        _forceCloseButton.Visibility = Visibility.Visible;
        _resultText.Text = AppLocalizer.T(
            "启动页正在等待关闭。若长时间停留，可关闭启动页。",
            "The startup page is waiting to close. You can close it if it stays here.");
    }

    private void CloseOrExit()
    {
        if (App.CurrentWindow == this)
        {
            Application.Current.Exit();
            return;
        }

        Close();
    }

    private void PostMessage(StartupSplashMessage message)
    {
        _pendingMessage = message;
        if (!_webReady || _webView.CoreWebView2 is null)
        {
            return;
        }

        try
        {
            _webView.CoreWebView2.PostWebMessageAsJson(message.ToJson());
        }
        catch
        {
        }
    }

    private StartupSplashMessage CreateThemeMessage()
        => new(
            "themeChanged",
            string.Empty,
            Theme: WebTheme(_settingsService.Current.Theme),
            ReducedMotion: !_settingsService.Current.AnimationsEnabled);

    private void ApplyTheme(string theme)
    {
        ModernUi.SetPalette(ShouldUseDarkPalette(theme));
        if (Content is FrameworkElement root)
        {
            root.RequestedTheme = ResolveElementTheme(theme);
        }

        PostMessage(CreateThemeMessage());
    }

    private void ConfigureWindow()
    {
        try
        {
            ExtendsContentIntoTitleBar = true;
            var hwnd = WindowNative.GetWindowHandle(this);
            _hwnd = hwnd;
            var windowId = Win32Interop.GetWindowIdFromWindow(hwnd);
            var appWindow = AppWindow.GetFromWindowId(windowId);
            if (appWindow.Presenter is OverlappedPresenter presenter)
            {
                presenter.SetBorderAndTitleBar(false, false);
                presenter.IsResizable = false;
                presenter.IsMaximizable = false;
                presenter.IsMinimizable = false;
            }

            var scale = GetWindowScale(hwnd);
            var width = DipToPixels(WindowWidthDip, scale);
            var height = DipToPixels(WindowHeightDip, scale);
            var displayArea = DisplayArea.GetFromWindowId(windowId, DisplayAreaFallback.Nearest);
            if (displayArea is not null)
            {
                var workArea = displayArea.WorkArea;
                appWindow.Resize(new SizeInt32(width, height));
                appWindow.Move(new PointInt32(
                    workArea.X + Math.Max(0, (workArea.Width - width) / 2),
                    workArea.Y + Math.Max(0, (workArea.Height - height) / 2)));
                ScheduleRoundedClipRefresh();
                return;
            }

            appWindow.Resize(new SizeInt32(width, height));
            ScheduleRoundedClipRefresh();
        }
        catch
        {
        }
    }

    private static string SeverityText(StartupCheckSeverity severity)
        => severity switch
        {
            StartupCheckSeverity.Critical => "critical",
            StartupCheckSeverity.Warning => "warning",
            _ => "info"
        };

    private static string WebTheme(string? theme)
        => ShouldUseDarkPalette(theme) ? "dark" : "light";

    private static ElementTheme ResolveElementTheme(string? theme)
    {
        return (theme ?? string.Empty).Trim().ToLowerInvariant() switch
        {
            "light" => ElementTheme.Light,
            "dark" => ElementTheme.Dark,
            _ => ElementTheme.Default
        };
    }

    private static bool ShouldUseDarkPalette(string? theme)
    {
        return (theme ?? string.Empty).Trim().ToLowerInvariant() switch
        {
            "light" => false,
            "dark" => true,
            _ => IsSystemDarkTheme()
        };
    }

    private static bool IsSystemDarkTheme()
    {
        try
        {
            var background = new UISettings().GetColorValue(UIColorType.Background);
            var luminance = (0.2126 * background.R) + (0.7152 * background.G) + (0.0722 * background.B);
            return luminance < 128;
        }
        catch
        {
            return false;
        }
    }

    private static double GetWindowScale(IntPtr hwnd)
    {
        try
        {
            var dpi = GetDpiForWindow(hwnd);
            return dpi > 0 ? dpi / 96.0 : 1.0;
        }
        catch
        {
            return 1.0;
        }
    }

    private static int DipToPixels(double dips, double scale)
    {
        return Math.Max(1, (int)Math.Round(dips * scale));
    }

    private void ScheduleRoundedClipRefresh()
    {
        if (_hwnd == IntPtr.Zero)
        {
            return;
        }

        var token = Interlocked.Increment(ref _roundedClipRefreshToken);
        ApplyWindowRoundedClipToCurrentBounds();

        _ = Task.Run(async () =>
        {
            foreach (var delay in new[] { 16, 80, 180, 360 })
            {
                await Task.Delay(delay).ConfigureAwait(false);
                _ = DispatcherQueue.TryEnqueue(() =>
                {
                    if (token == _roundedClipRefreshToken)
                    {
                        ApplyWindowRoundedClipToCurrentBounds();
                    }
                });
            }
        });
    }

    private void ApplyWindowRoundedClipToCurrentBounds()
    {
        var hwnd = _hwnd;
        if (hwnd == IntPtr.Zero)
        {
            return;
        }

        if (!GetWindowRect(hwnd, out var rect))
        {
            return;
        }

        var width = Math.Max(1, rect.Right - rect.Left);
        var height = Math.Max(1, rect.Bottom - rect.Top);
        ApplyWindowRoundedClip(hwnd, width, height, GetWindowScale(hwnd));
    }

    private static void ApplyWindowRoundedClip(IntPtr hwnd, int width, int height, double scale)
    {
        try
        {
            var preference = DwmWindowCornerPreferenceRound;
            _ = DwmSetWindowAttribute(
                hwnd,
                DwmWindowCornerPreference,
                ref preference,
                Marshal.SizeOf<int>());

            var radius = Math.Max(1, DipToPixels(WindowClipRadiusDip, scale));
            var region = CreateRoundRectRgn(0, 0, width, height, radius * 2, radius * 2);
            if (region == IntPtr.Zero)
            {
                return;
            }

            if (SetWindowRgn(hwnd, region, true) == 0)
            {
                _ = DeleteObject(region);
                return;
            }

            _ = RedrawWindow(
                hwnd,
                IntPtr.Zero,
                IntPtr.Zero,
                RedrawInvalidate | RedrawFrame | RedrawAllChildren | RedrawUpdateNow);
        }
        catch
        {
        }
    }

    [DllImport("user32.dll")]
    private static extern uint GetDpiForWindow(IntPtr hwnd);

    [StructLayout(LayoutKind.Sequential)]
    private struct Win32Rect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool GetWindowRect(IntPtr hwnd, out Win32Rect rect);

    private const int DwmWindowCornerPreference = 33;
    private const int DwmWindowCornerPreferenceRound = 2;
    private const uint RedrawInvalidate = 0x0001;
    private const uint RedrawUpdateNow = 0x0100;
    private const uint RedrawFrame = 0x0400;
    private const uint RedrawAllChildren = 0x0080;

    [DllImport("dwmapi.dll", PreserveSig = true)]
    private static extern int DwmSetWindowAttribute(IntPtr hwnd, int dwAttribute, ref int pvAttribute, int cbAttribute);

    [DllImport("gdi32.dll", SetLastError = true)]
    private static extern IntPtr CreateRoundRectRgn(int x1, int y1, int x2, int y2, int width, int height);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern int SetWindowRgn(IntPtr hwnd, IntPtr hRgn, bool redraw);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool RedrawWindow(IntPtr hwnd, IntPtr updateRect, IntPtr updateRegion, uint flags);

    [DllImport("gdi32.dll", SetLastError = true)]
    private static extern bool DeleteObject(IntPtr hObject);
}
