@namespace Lumeo
@inject Lumeo.Services.IComponentInteropService Interop

@if (OnClick.HasDelegate)
{
    <div @ref="_el"
         class="@CssClass"
         role="button"
         tabindex="0"
         @onclick="OnClick"
         @onkeydown="HandleKeyDown"
         @attributes="AdditionalAttributes">
        @ChildContent
    </div>
}
else
{
    <div class="@CssClass" @attributes="AdditionalAttributes">
        @ChildContent
    </div>
}

@code {
    [Parameter] public RenderFragment? ChildContent { get; set; }
    [Parameter] public string? Class { get; set; }

    /// <summary>
    /// Optional click handler. When set, the card becomes a button-role
    /// interactive surface with <c>cursor-pointer</c>, focus-visible ring,
    /// keyboard activation, and honours <see cref="PressEffect"/>.
    /// </summary>
    [Parameter] public EventCallback<Microsoft.AspNetCore.Components.Web.MouseEventArgs> OnClick { get; set; }

    /// <summary>
    /// Visual feedback when the card is pressed (only applies when
    /// <see cref="OnClick"/> is bound). Default is
    /// <see cref="Button.ButtonPressEffect.None"/>.
    /// </summary>
    [Parameter] public Button.ButtonPressEffect PressEffect { get; set; } = Button.ButtonPressEffect.None;

    [Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object>? AdditionalAttributes { get; set; }

    private Microsoft.AspNetCore.Components.ElementReference _el;

    private bool IsInteractive => OnClick.HasDelegate;

    private string? PressEffectClass => PressEffect switch
    {
        Button.ButtonPressEffect.Scale => "lumeo-press-scale",
        Button.ButtonPressEffect.Brightness => "lumeo-press-brightness",
        Button.ButtonPressEffect.Ripple => "lumeo-press-ripple",
        _ => null
    };

    private string CssClass => string.Join(" ", new[]
    {
        "rounded-lg border border-border bg-card text-card-foreground",
        IsInteractive ? "cursor-pointer transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 hover:bg-accent/30" : null,
        IsInteractive ? PressEffectClass : null,
        Class
    }.Where(s => !string.IsNullOrWhiteSpace(s)));

    private async Task HandleKeyDown(Microsoft.AspNetCore.Components.Web.KeyboardEventArgs e)
    {
        if (!IsInteractive) return;
        if (e.Key == "Enter" || e.Key == " ")
        {
            await OnClick.InvokeAsync(new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && IsInteractive && PressEffect == Button.ButtonPressEffect.Ripple)
        {
            try
            {
                await Interop.RippleAttachAsync(_el);
            }
            catch (Microsoft.JSInterop.JSDisconnectedException) { }
        }
    }
}
