@inject IJSRuntime JsRuntime
@implements IAsyncDisposable


<head>
    <link rel="stylesheet" href="assets/vendor/ckeditor5-content.css" />
</head>
<style>
    .ck-content * {
        all: revert;
    }

    .ck-balloon-panel {
        z-index: 9999 !important
    }

</style>
<div class="editor"></div>

@code 
{



    [Parameter]
    public string Text { get; set; } = string.Empty;

    [Parameter]
    public EventCallback<string> TextChanged { get; set; }

    private bool isTextSeted = false;

    [JSInvokable("MyMethod")]
    public void HandleEditorBlur(string data)
    {
        Text = data;
        TextChanged.InvokeAsync(data);
        StateHasChanged(); // Ensure UI updates
    }


    protected override async Task OnParametersSetAsync()
    {
        if (!string.IsNullOrEmpty(Text) && !isTextSeted)
        {
            try
            {
                await JsRuntime.InvokeVoidAsync("setData", Text);
                isTextSeted = true;
            }
            catch (Exception e)
            {

            }
        }
        await base.OnParametersSetAsync();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {

        if (firstRender)
        {
            var lDotNetReference = DotNetObjectReference.Create(this);
            await JsRuntime.InvokeVoidAsync("GLOBAL.SetDotnetReference", lDotNetReference);
            await JsRuntime.InvokeVoidAsync("initializeCKEditor", Text);
            await base.OnAfterRenderAsync(firstRender);
        }
    }

    public void Dispose()
    {
        JsRuntime.InvokeVoidAsync("destroyEditor", Text);
    }

    public async ValueTask DisposeAsync()
    {
        await JsRuntime.InvokeVoidAsync("destroyEditor", Text);
    }

}