@namespace OpenArchival.Blazor.FileViewer

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

@inject IJSRuntime JSRuntime

<div @ref="_imageContainer" style="height:auto; width:100%; display: flex; justify-content: center;">
    <img src="@($"/api/files/{File.Id}/large")"
         @onload="MeasureHeight"
         style="max-height: 80vh; max-width: 100%; object-fit: contain; display: block;" />
</div>

@code {
    [Parameter]
    public required FilePathListing File { get; set; }
    
    [Parameter]
    public EventCallback<int> OnHeightMeasured { get; set; }

    private ElementReference _imageContainer;

    private async Task MeasureHeight()
    {
        try 
        {
            var height = await JSRuntime.InvokeAsync<double>("centerImageAndGetHeight", _imageContainer);
            await OnHeightMeasured.InvokeAsync((int)Math.Ceiling(height));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error measuring image height: {ex.Message}");
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await MeasureHeight();
        }
    }
}