@if (IsOpen)
{
    <button
        type="button"
        class="surface-drawer-backdrop"
        aria-label="@CloseLabel"
        @onclick="HandleCloseAsync"></button>

    <aside class="@BuildCssClass()" aria-label="@AriaLabel">
        @if (!string.IsNullOrWhiteSpace(Title) || HeaderContent is not null || OnClose.HasDelegate)
        {
            <header class="surface-drawer-header">
                <div>
                    @if (!string.IsNullOrWhiteSpace(Title))
                    {
                        <strong class="surface-drawer-title">@Title</strong>
                    }
                </div>

                <div class="surface-drawer-header-actions">
                    @HeaderContent
                    @if (OnClose.HasDelegate)
                    {
                        <button type="button" class="btn btn-link" @onclick="HandleCloseAsync">Close</button>
                    }
                </div>
            </header>
        }

        <div class="surface-drawer-body">
            @ChildContent
        </div>
    </aside>
}

@code {
    [Parameter]
    public bool IsOpen { get; set; }

    [Parameter]
    public string Placement { get; set; } = "end";

    [Parameter]
    public string AriaLabel { get; set; } = "Drawer";

    [Parameter]
    public string CloseLabel { get; set; } = "Close panel";

    [Parameter]
    public string? Title { get; set; }

    [Parameter]
    public RenderFragment? HeaderContent { get; set; }

    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    [Parameter]
    public EventCallback OnClose { get; set; }

    [Parameter]
    public string? CssClass { get; set; }

    private string BuildCssClass()
    {
        var classes = new List<string> { "surface-drawer", $"is-{Placement.Trim().ToLowerInvariant()}" };
        if (!string.IsNullOrWhiteSpace(CssClass))
        {
            classes.Add(CssClass);
        }

        return string.Join(' ', classes);
    }

    private Task HandleCloseAsync() =>
        OnClose.InvokeAsync();
}
