@inject IJSRuntime JSRuntime
@implements IAsyncDisposable

<div @onkeydown="KeyWasPressed" @onkeydown:preventDefault="@preventDefault" class="@CssClass">
    @ChildContent
</div>

@code {
    /// <summary>
    /// Callback when Enter key is pressed.
    /// </summary>
    [Parameter]
    public EventCallback OnEnter { get; set; }

    /// <summary>
    /// The child content of the component.
    /// </summary>
    [Parameter]
    public required RenderFragment ChildContent { get; set; }

    /// <summary>
    /// CSS class string to apply to the wrapper div.
    /// </summary>
    [Parameter]
    public string CssClass { get; set; } = "modal-dialog fixed inset-0 z-50 overflow-auto bg-gray-500 bg-opacity-75 flex items-center justify-center";

    /// <summary>
    /// Determines if the default behavior should be prevented for keyboard events.
    /// </summary>
    [Parameter]
    public bool preventDefault { get; set; } = false;

    /// <summary>
    /// Handle keyboard events.
    /// </summary>
    private async Task KeyWasPressed(KeyboardEventArgs e)
    {
        // Listen for Enter key and submit the modal
        if (e.Key == "Enter")
        {
            preventDefault = true;
            await OnEnter.InvokeAsync();
        }
    }

    /// <inheritdoc />
    public ValueTask DisposeAsync()
    {
        return ValueTask.CompletedTask;
    }
}
