@inject IJSRuntime JsRuntime
@implements IAsyncDisposable

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

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

</style>
<div class="editor"></div>
<script type="text/javascript">


    function destroyEditor() {
        // document.querySelector('.editor').ckeditorInstance.destroy();
        window.editor = null;
    }
    function lunchEditor(data) {
        if (!document.querySelector('.editor')) return
        if (window.editor) return
        ClassicEditor.create(document.querySelector('.editor'), {
            htmlSupport: {
                allow: [
                    {
                        name: 'iframe',
                        attributes: true,
                        classes: true,
                        styles: true
                    }
                ]
            }
        })
            .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);
    }

    function setData(data) {
        if (!!window.editor.date && window.editor.data != data) {
            window.editor.setData(data);
        }
    }
</script>


@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("window.setData", Text);
                isTextSeted = true;
            }
            catch (Exception e)
            {

            }
        }
        await 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);
    }

}
