@using DeepDrftModels.DTOs
@using DeepDrftPublic.Client.Controls.AudioPlayerBar
@using DeepDrftPublic.Client.Layout
@using DeepDrftPublic.Client.Services

@page "/FramePlayer"
@layout EmbedLayout

<AudioPlayerBar Fixed />

@code {
    [CascadingParameter] public IStreamingPlayerService? PlayerService { get; set; }
    [SupplyParameterFromQuery] public string? TrackEntryKey { get; set; }
    [Inject] public required ITrackDataService TrackDataService { get; set; }

    private string? _stagedKey;

    protected override async Task OnParametersSetAsync()
    {
        if (PlayerService is null || string.IsNullOrWhiteSpace(TrackEntryKey)) return;

        // OnParametersSetAsync can fire repeatedly (and once per render pass); only act when the
        // key actually changes so we don't re-fetch on every parameter set.
        if (TrackEntryKey == _stagedKey) return;
        _stagedKey = TrackEntryKey;

        var result = await TrackDataService.GetTrack(TrackEntryKey);
        if (result.Success && result.Value is not null)
        {
            // Stage only — no audio context, no streaming. The browser blocks audio until a user
            // gesture, so the embed shows the track ready and the first play click (handled in
            // AudioPlayerBar) calls SelectTrackStreaming. This also keeps this pass free of JS
            // interop, so it works whether it runs during prerender or after WASM is interactive.
            await PlayerService.StageTrack(result.Value);
        }
        // On failure, leave the bar idle; a stream-level error surfaces via PlayerService.ErrorMessage.
    }
}