@namespace OpenArchival.Blazor.FileViewer

@implements IFileViewer
@using Microsoft.JSInterop
@using MudBlazor
@using OpenArchival.DataAccess
@inject IJSRuntime JSRuntime

<div @ref="_textContainer" style="width:100%; max-height: 1100px; overflow-y: auto; background-color: var(--mud-palette-background-grey); padding: 16px; border-radius: 4px;">
    <MudText Typo="Typo.body1" Style="white-space: pre-wrap; font-family: 'Courier New', Courier, monospace; color: var(--mud-palette-text-primary);">
        @_textContent
    </MudText>
</div>

@code {
    [Parameter]
    public required FilePathListing File { get; set; }

    [Parameter]
    public EventCallback<int> OnHeightMeasured { get; set; }

    private string? _textContent;
    private ElementReference _textContainer;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            if (System.IO.File.Exists(File.Path))
            {
                _textContent = await System.IO.File.ReadAllTextAsync(File.Path);
            }
            else
            {
                _textContent = "Error: File not found on disk.";
            }
        }
        catch (Exception ex)
        {
            _textContent = $"Error reading file: {ex.Message}";
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        try
        {
            var height = await JSRuntime.InvokeAsync<int>("getElementHeight", _textContainer);
            // Add some padding to avoid scrollbars if possible, or just use what it is
            await OnHeightMeasured.InvokeAsync(height);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error measuring text height: {ex.Message}");
        }
    }
}
