@page "/items/{Id:int}"
@implements IAsyncDisposable
@inject LifecycleLog Log

<PageTitle>Item @Id</PageTitle>

<main>
    <h1>Item @Id</h1>
    <p class="details">@(details ?? "Fetching details…")</p>

    <div class="row">
        @if (Id > 1)
        {
            <a class="chip" href="items/@(Id - 1)">Previous</a>
        }
        <a class="chip" href="items/@(Id + 1)">Next</a>
        <a class="chip" href="">Home</a>
    </div>

    <div class="panel">
        <p>Component instance <strong>#@instance</strong>, alive for <strong>@seconds s</strong>.</p>
        <p class="muted">Previous and Next keep this instance, so the seconds keep counting. Home disposes it.</p>
    </div>

    <div class="panel">
        <label class="check"><input type="checkbox" @bind="paused" /> Pause rendering</label>
        <div class="row">
            <button class="primary" @onclick="() => clicks++">Click</button>
            <span>Clicks: <strong>@clicks</strong></span>
        </div>
        <p class="muted">While paused, ShouldRender returns false. Clicks and seconds still count, but the screen does not change until you clear the box.</p>
    </div>

    <h2>Lifecycle log</h2>
    <ol class="log">
        @foreach (var entry in Log.Entries)
        {
            <li>@entry</li>
        }
    </ol>
</main>

@code {
    // Filled from the {Id:int} segment of the address.
    [Parameter]
    public int Id { get; set; }

    private int instance;
    private int seconds;
    private int clicks;
    private bool paused;
    private string? details;
    private Timer? timer;

    // Runs first, every time the Router passes parameters. Id still has its old value here.
    public override async Task SetParametersAsync(ParameterView parameters)
    {
        var next = parameters.GetValueOrDefault<int>(nameof(Id));
        Log.Add($"SetParametersAsync: Id {Id} -> {next}");
        await base.SetParametersAsync(parameters); // assigns Id, then runs the methods below
    }

    // Runs once per component instance.
    protected override void OnInitialized()
    {
        instance = Log.NextInstance();
        timer = new Timer(OnTimer, null, 1000, 1000);
        Log.Add($"OnInitialized: instance #{instance}, timer started");
    }

    // Also once. The first render happens while this method awaits.
    protected override async Task OnInitializedAsync()
    {
        await Task.Delay(200);
        Log.Add("OnInitializedAsync: finished");
    }

    // Runs after initialization and again every time Id changes.
    protected override void OnParametersSet()
    {
        paused = false;
        Log.Add($"OnParametersSet: Id = {Id}");
    }

    protected override async Task OnParametersSetAsync()
    {
        details = null;
        await Task.Delay(500); // stands in for an HTTP call that depends on Id
        details = $"Details for item {Id}, fetched in OnParametersSetAsync.";
    }

    // Runs after the browser's page has been updated. firstRender is true once per instance.
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender) Log.Add("OnAfterRender: firstRender = true");
    }

    // Asked before every render except the first one.
    protected override bool ShouldRender() => !paused;

    // The timer calls this on its own schedule, outside Blazor's rendering.
    // InvokeAsync runs the update on the renderer, where StateHasChanged belongs.
    private void OnTimer(object? state) => _ = InvokeAsync(() =>
    {
        seconds++;
        StateHasChanged();
    });

    // Blazor calls this when the component leaves the page. Without it, the timer would keep firing.
    public async ValueTask DisposeAsync()
    {
        if (timer is not null) await timer.DisposeAsync();
        Log.Add($"DisposeAsync: instance #{instance}, timer stopped");
    }
}
