using Microsoft.AspNetCore.Components.WebView;

namespace SilverOS.Welcome.App;

public partial class MainPage : ContentPage
{
	bool _splashDismissed;

	public MainPage()
	{
		InitializeComponent();
		Diag.Log("MainPage ctor");
	}

	// Fires once the platform WebView2 is created. If this never appears in the log,
	// WebView2 environment creation failed (the real cause of a blank wizard).
	void OnBlazorInitialized(object? sender, BlazorWebViewInitializedEventArgs e)
	{
		Diag.Log("BlazorWebViewInitialized");
#if WINDOWS
		try
		{
			var wv = e.WebView; // Microsoft.UI.Xaml.Controls.WebView2
			wv.NavigationCompleted += (a, b) =>
			{
				Diag.Log($"WV2 NavigationCompleted ok={b.IsSuccess} status={b.WebErrorStatus}");
				// First completed navigation = the WebView has content on screen.
				// Drop the native splash so the (visually identical) in-page splash
				// carries through Blazor's final boot without a flash of blank.
				if (b.IsSuccess) DismissSplash();
			};
			if (wv.CoreWebView2 is not null)
				wv.CoreWebView2.ProcessFailed += (a, b) =>
					Diag.Log("WV2 ProcessFailed: " + b.ProcessFailedKind);
		}
		catch (Exception ex) { Diag.Log("WV2 hook failed: " + ex.Message); }
#endif
	}

	// Fade the native splash out once, then collapse it so it never intercepts input.
	void DismissSplash()
	{
		if (_splashDismissed) return;
		_splashDismissed = true;
		MainThread.BeginInvokeOnMainThread(async () =>
		{
			try
			{
				await SplashOverlay.FadeTo(0, 250, Easing.CubicOut);
			}
			catch { /* fade is cosmetic — never block on it */ }
			finally
			{
				SplashOverlay.IsVisible = false;
				SplashOverlay.InputTransparent = true;
			}
		});
	}

	void OnUrlLoading(object? sender, UrlLoadingEventArgs e)
		=> Diag.Log("UrlLoading: " + e.Url);
}
