@namespace Lumeo

<button class="@CssClass" tabindex="@TabIndex" @onclick="HandleClick" @onmouseenter="HandleMouseEnter" @onkeydown="HandleKeyDown" @attributes="AdditionalAttributes">
    @ChildContent
</button>

@code {
    [CascadingParameter] public Menubar.MenubarContext Context { get; set; } = default!;
    [CascadingParameter] public MenubarMenu.MenubarMenuContext MenuContext { 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 bool IsOpen => Context.OpenMenuId == MenuContext.MenuId;

    // Roving tabindex: the active (open) trigger — or the first registered trigger
    // when none is open — gets tabindex=0; all others get tabindex=-1.
    private string TabIndex
    {
        get
        {
            if (IsOpen) return "0";
            if (Context.OpenMenuId is null && Context.MenuIds.Count > 0 && Context.MenuIds[0] == MenuContext.MenuId) return "0";
            return "-1";
        }
    }

    private string CssClass => string.Join(" ", new[] { "flex cursor-default select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none", IsOpen ? "bg-accent text-accent-foreground" : null, Class }.Where(s => !string.IsNullOrWhiteSpace(s)));

    private async Task HandleClick()
    {
        if (IsOpen)
        {
            await Context.SetOpenMenuId.InvokeAsync(null);
        }
        else
        {
            await Context.SetOpenMenuId.InvokeAsync(MenuContext.MenuId);
        }
    }

    private async Task HandleMouseEnter()
    {
        if (Context.AnyOpen)
        {
            await Context.SetOpenMenuId.InvokeAsync(MenuContext.MenuId);
        }
    }

    private async Task HandleKeyDown(KeyboardEventArgs e)
    {
        switch (e.Key)
        {
            case "ArrowDown":
            case "Enter":
            case " ":
                if (!IsOpen)
                {
                    await Context.SetOpenMenuId.InvokeAsync(MenuContext.MenuId);
                }
                break;
            case "ArrowLeft":
                Context.NavigateMenus(-1);
                break;
            case "ArrowRight":
                Context.NavigateMenus(1);
                break;
            case "Escape":
                if (IsOpen)
                {
                    await Context.SetOpenMenuId.InvokeAsync(null);
                }
                break;
        }
    }
}
