@inject NavigationManager Navigation

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
            return;

        var returnUrl = Uri.EscapeDataString(GetSafeReturnUrl());
        Navigation.NavigateTo($"/admin/login?returnUrl={returnUrl}", forceLoad: true, replace: true);
    }

    private string GetSafeReturnUrl()
    {
        try
        {
            var current = new Uri(Navigation.Uri);
            var baseUri = new Uri(Navigation.BaseUri);

            if (current.IsAbsoluteUri &&
                string.Equals(current.Scheme, baseUri.Scheme, StringComparison.OrdinalIgnoreCase) &&
                string.Equals(current.Authority, baseUri.Authority, StringComparison.OrdinalIgnoreCase) &&
                current.AbsolutePath.StartsWith(baseUri.AbsolutePath, StringComparison.OrdinalIgnoreCase))
            {
                var relative = current.AbsolutePath[baseUri.AbsolutePath.Length..] + current.Query + current.Fragment;
                return string.IsNullOrWhiteSpace(relative) ? "dashboard" : relative.TrimStart('/');
            }
        }
        catch
        {
            // Fall through to a safe default.
        }

        return "/admin/dashboard";
    }
}
