using DeepDrftModels.DTOs;
using DeepDrftPublic.Client.ViewModels;
using Microsoft.AspNetCore.Components;

namespace DeepDrftPublic.Client.Pages;

public partial class TrackDetail : ComponentBase, IDisposable
{
    private const string PersistKey = "track-detail";

    [Parameter] public required string EntryKey { get; set; }
    [Inject] public required TrackDetailViewModel ViewModel { get; set; }
    [Inject] public required PersistentComponentState PersistentState { get; set; }

    private PersistingComponentStateSubscription _persistingSubscription;

    protected override async Task OnInitializedAsync()
    {
        // Carry the prerendered track across the prerender -> interactive (WASM) seam.
        // Without this, the WASM pass gets a fresh scoped ViewModel, re-renders the
        // skeleton, and re-fetches. Mirror the TracksView bridge: persist on the way
        // out of prerender, restore on the interactive pass, and only fetch on a miss.
        _persistingSubscription = PersistentState.RegisterOnPersisting(PersistTrack);

        if (PersistentState.TryTakeFromJson<TrackDto>(PersistKey, out var restored) && restored is not null)
        {
            ViewModel.Track = restored;
            ViewModel.IsLoading = false;
        }
        else
        {
            await ViewModel.Load(EntryKey);
        }
    }

    private Task PersistTrack()
    {
        if (ViewModel.Track is not null)
        {
            PersistentState.PersistAsJson(PersistKey, ViewModel.Track);
        }
        return Task.CompletedTask;
    }

    public void Dispose() => _persistingSubscription.Dispose();
}
