@* Lives in the header. It is neither parent nor child of the shop page,
   so it hears about cart changes through CartState.OnChange. *@
@implements IDisposable
@inject CartState Cart

<span class="badge" role="status">
    Cart: @Cart.Count · @Currency.Format(Cart.TotalEur)
    <button class="empty" @onclick="Cart.Clear" disabled="@(Cart.Count == 0)">Empty</button>
</span>

@code {
    // Filled by the CascadingValue in App.razor.
    [CascadingParameter] public Currency Currency { get; set; } = Currency.Euro;

    protected override void OnInitialized() => Cart.OnChange += CartChanged;

    // The event may fire outside Blazor's own event handling (here: a timer).
    // InvokeAsync runs StateHasChanged on the renderer's synchronization context.
    private void CartChanged() => _ = InvokeAsync(StateHasChanged);

    // Without this, the service would keep calling a component that is gone.
    public void Dispose() => Cart.OnChange -= CartChanged;
}
