@namespace Lumeo
@implements IAsyncDisposable

@if (Context.IsOpen)
{
    <div class="fixed inset-0 z-50 flex items-center justify-center">
        <div class="fixed inset-0 bg-black/80 animate-fade-in"></div>
        <div id="@_contentId" class="@CssClass" role="alertdialog" aria-modal="true" aria-labelledby="@Context.TitleId" aria-describedby="@Context.DescriptionId" @onkeydown="HandleKeyDown" tabindex="-1" @attributes="AdditionalAttributes">
            @ChildContent
        </div>
    </div>
}

@inject ComponentInteropService Interop

@code {
    [CascadingParameter] public AlertDialog.AlertDialogContext Context { get; set; } = default!;
    [Parameter] public RenderFragment? ChildContent { get; set; }
    [Parameter] public string? Class { get; set; }
    [Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object>? AdditionalAttributes { get; set; }

    private readonly string _contentId = $"alertdialog-{Guid.NewGuid():N}";
    private bool _wasOpen;

    private string CssClass => $"relative z-50 grid w-full max-w-lg gap-4 bg-background p-6 shadow-lg animate-zoom-in sm:rounded-lg {Class}".Trim();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (Context.IsOpen && !_wasOpen)
        {
            await Interop.LockScroll();
            await Interop.SetupFocusTrap(_contentId);
            _wasOpen = true;
        }
        else if (!Context.IsOpen && _wasOpen)
        {
            await Cleanup();
            _wasOpen = false;
        }
    }

    private async Task HandleKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Escape")
        {
            await Context.SetOpen.InvokeAsync(false);
        }
    }

    private async Task Cleanup()
    {
        try
        {
            await Interop.RemoveFocusTrap(_contentId);
            await Interop.UnlockScroll();
        }
        catch (JSDisconnectedException) { }
    }

    public async ValueTask DisposeAsync()
    {
        if (_wasOpen)
        {
            await Cleanup();
        }
    }
}
