@namespace Lumeo

<button id="@ItemContext.TriggerId"
        type="button"
        class="@CssClass"
        @onclick="HandleClick"
        @onpointerenter="HandlePointerEnter"
        @attributes="AdditionalAttributes">
    @ChildContent
    <Blazicon Svg="Lucide.ChevronDown" class="@ChevronClasses" />
</button>

@code {
    [CascadingParameter] public NavigationMenu.NavigationMenuContext Context { get; set; } = default!;
    [CascadingParameter] public NavigationMenuItem.NavigationMenuItemContext ItemContext { 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 IsActive => Context.ActiveItemId == ItemContext.ItemId;

    private string CssClass => string.Join(" ", new[] { "group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50", IsActive ? "bg-accent/50" : null, Class }.Where(s => !string.IsNullOrWhiteSpace(s)));

    private string ChevronClasses => string.Join(" ", new[] { "relative top-[1px] ml-1 h-3 w-3 transition-transform duration-200", IsActive ? "rotate-180" : null }.Where(s => !string.IsNullOrWhiteSpace(s)));

    private async Task HandleClick()
    {
        if (IsActive)
        {
            await Context.SetActiveItemId.InvokeAsync(null);
        }
        else
        {
            await Context.SetActiveItemId.InvokeAsync(ItemContext.ItemId);
        }
    }

    // rc.44 — only auto-open for mouse pointers. On touch devices the browser
    // emulates pointerenter on tap; combined with the parent's hover-leave on
    // finger-lift, this would briefly flash the submenu before closing it.
    // Touch users open via @onclick.
    private async Task HandlePointerEnter(PointerEventArgs e)
    {
        if (e.PointerType != "mouse") return;
        await Context.SetActiveItemId.InvokeAsync(ItemContext.ItemId);
    }
}
