@inject IToastService toastService

@implements IDisposable

@if (Toast == null)
{
    <div>Add toast object...</div>
}
else
{
    <div onclick="@Dismiss" style="opacity: @Opacity()" class="toastContainer @Toast.SeverityType.ToLower()">
        <div class="toastTitle">
            @Toast.Title
        </div>
        <div>
            @Toast.Message
        </div>
    </div>
}

<style>
     .toastContainer {
        border: 4px solid;
        border-radius: 4px;
        padding: 16px;
        display: flex;
        flex-direction: column;
        justify-items: stretch;
        width: 250px;
        cursor: pointer;
    }
    
    .@SeverityType.Warning.ToLower() {
        background-color: var(--severity-warning-color);
        border-color: var(--severity-warning-border-color);
    }

    .@SeverityType.Error.ToLower() {
        background-color: var(--severity-error-color);
        border-color: var(--severity-error-border-color);
    }

    .@SeverityType.Information.ToLower() {
        background-color: var(--severity-information-color);
        border-color: var(--severity-information-border-color);
    }

    .@SeverityType.Success.ToLower() {
        background-color: var(--severity-success-color);
        border-color: var(--severity-success-border-color);
    }

    .toastTitle {
        font-weight: 800;
    }

</style>

@code {

    [Parameter]
    public ToastModel? Toast { get; set; } = default!;

    private float removalTime = 1300;
    private float fadeoutTime = 1200;

    private float Opacity()
    {
        if (Toast!.Age < fadeoutTime)
        {
            return 1;
        }

        return 1.0f - (Toast.Age - fadeoutTime) / (removalTime - fadeoutTime);
    }

    protected override void OnInitialized()
    {
        toastService.Subscribe(OnUpdate);
    }

    void Dismiss()
    {
        toastService.RemoveToast(Toast!);
    }

    public void Dispose()
    {
        toastService.Unsubscribe(OnUpdate);
    }

    void OnUpdate()
    {
        if (Toast!.Age > removalTime)
        {
            toastService.RemoveToast(Toast);
        }
    }

}