@inject IJSRuntime JsRuntime
@implements IAsyncDisposable

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

<script type="text/javascript">
    function destroyEditor() {
        // document.querySelector('.editor').ckeditorInstance.destroy();
        window.editor = null;
        console.log('Editor Destroyed');
    }
    function lunchEditor(data) {
        if (!document.querySelector('.editor')) return
        if (window.editor) return
        ClassicEditor.create(document.querySelector('.editor'), {
                // Editor configuration.
            })
            .then(editor => {
                window.editor = editor;
                window.editor.setData(data);
                editor.editing.view.document.on('blur', () => {
                    GLOBAL.DotNetReference.invokeMethodAsync('MyMethod',window.editor.getData());
                });
            })
            .catch(handleSampleError);
    }
    var GLOBAL = {};
    GLOBAL.DotNetReference = null;
    GLOBAL.SetDotnetReference = function (pDotNetReference) {
        GLOBAL.DotNetReference = pDotNetReference;
    };


    function handleSampleError(error) {
        const issueUrl = 'https://github.com/ckeditor/ckeditor5/issues';

        const message = [
            'Oops, something went wrong!',
            `Please, report the following error on ${issueUrl} with the build id "pws0dnpd0jqj-zi42lsl7aqxa" and the error stack trace:`
        ].join('\n');

        console.error(message);
        console.error(error);
    }
</script>


@code {



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

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

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


    protected override Task OnParametersSetAsync()
    {
        return base.OnParametersSetAsync();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        
        var lDotNetReference = DotNetObjectReference.Create(this);
        await JsRuntime.InvokeVoidAsync("GLOBAL.SetDotnetReference", lDotNetReference);

        await JsRuntime.InvokeVoidAsync("window.lunchEditor", Text);
        await base.OnAfterRenderAsync(firstRender);
    }

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

    public async ValueTask DisposeAsync()
    {

        await JsRuntime.InvokeVoidAsync("window.destroyEditor", Text);
    }

}
