@namespace OpenArchival.Blazor.FileViewer

@implements IFileViewer
@using Microsoft.JSInterop
@using MudBlazor
@using OpenArchival.DataAccess

<div @ref="_imageContainer" style="height:100%; width:100%;">
    <MudImage Src="@($"/api/files/{File.Id}")"
              Style="max-height: 100%; max-width: 100%; object-fit: contain;"></MudImage>
</div>

@inject IJSRuntime JSRuntime;
@code {
    [Parameter]
    public required FilePathListing File { get; set; }
    public int Height { get; private set; }
    [Parameter]
    public EventCallback<int> OnHeightMeasured { get; set; }

    private ElementReference _imageContainer;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                await Task.Delay(50);
                Height = await JSRuntime.InvokeAsync<int>("centerImageAndGetHeight", _imageContainer);

                if (Height > 0)
                {
                    await OnHeightMeasured.InvokeAsync(Height);
                }
            }
            catch (JSException ex)
            {
                Console.WriteLine($"[ERROR] JavaScript Interop failed: {ex.Message}");
            }
        }
    }
}