@using Microsoft.AspNetCore.Components.Sections
@inject NavigationManager NavigationManager
@implements IDisposable

<SectionContent SectionName="Canonical">
    <link rel="canonical" href="@CanonicalUrl" />
</SectionContent>

@code {
    private string CanonicalUrl => GetCanonicalUrl();

    protected override void OnInitialized()
    {
        NavigationManager.LocationChanged += OnLocationChanged;
    }

    public void Dispose()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;
    }

    private void OnLocationChanged(object sender, LocationChangedEventArgs e)
    {
        StateHasChanged();
    }

    private string GetCanonicalUrl()
    {
        var current = NavigationManager.Uri;

        if (Uri.TryCreate(current, UriKind.Absolute, out var absolute))
        {
            return absolute.GetLeftPart(UriPartial.Path);
        }

        return current;
    }
}