@namespace SufiChain.SufiBlazor.Components.Overlays
@implements IDisposable
@inject IJSRuntime JSRuntime

<div class="sb-context-menu-trigger" @ref="_triggerRef" @oncontextmenu="OnContextMenu" @oncontextmenu:preventDefault="true">
    @ChildContent
</div>

@if (_isOpen)
{
    <div class="sb-context-menu-overlay" @onclick="Close">
        <div class="sb-context-menu @Class" 
             style="left: @(_x)px; top: @(_y)px"
             @onclick:stopPropagation="true">
            @MenuContent
        </div>
    </div>
}

@code {
    private ElementReference _triggerRef;
    private bool _isOpen;
    private double _x;
    private double _y;
    
    /// <summary>
    /// Trigger content.
    /// </summary>
    [Parameter]
    public RenderFragment? ChildContent { get; set; }
    
    /// <summary>
    /// Menu content.
    /// </summary>
    [Parameter]
    public RenderFragment? MenuContent { get; set; }
    
    /// <summary>
    /// Whether the context menu is disabled.
    /// </summary>
    [Parameter]
    public bool Disabled { get; set; }
    
    /// <summary>
    /// Callback before menu opens.
    /// </summary>
    [Parameter]
    public EventCallback<SbContextMenuEventArgs> OnOpen { get; set; }
    
    /// <summary>
    /// Callback when menu closes.
    /// </summary>
    [Parameter]
    public EventCallback OnClose { get; set; }
    
    /// <summary>
    /// Additional CSS classes.
    /// </summary>
    [Parameter]
    public string? Class { get; set; }
    
    private async Task OnContextMenu(MouseEventArgs e)
    {
        if (Disabled) return;
        
        var args = new SbContextMenuEventArgs { X = e.ClientX, Y = e.ClientY };
        await OnOpen.InvokeAsync(args);
        
        if (!args.Cancel)
        {
            _x = e.ClientX;
            _y = e.ClientY;
            _isOpen = true;
        }
    }
    
    /// <summary>
    /// Close the context menu.
    /// </summary>
    public async Task Close()
    {
        _isOpen = false;
        await OnClose.InvokeAsync();
    }
    
    public void Dispose()
    {
        // Cleanup if needed
    }
}

/// <summary>
/// Context menu event arguments.
/// </summary>
public class SbContextMenuEventArgs
{
    /// <summary>
    /// X coordinate.
    /// </summary>
    public double X { get; set; }
    
    /// <summary>
    /// Y coordinate.
    /// </summary>
    public double Y { get; set; }
    
    /// <summary>
    /// Whether to cancel opening the menu.
    /// </summary>
    public bool Cancel { get; set; }
}
