@using Microsoft.AspNetCore.Components.Web
@inject IJSRuntime JS

@*
    Monaco-backed C# code editor (Phase 7 Stream F). Progressive enhancement:
    textarea renders immediately, Monaco mounts via JS interop after first render.
    Monaco script tags are loaded once from the parent layout (wwwroot/js/monaco-loader.js
    pulls the CDN bundle).

    Stream F keeps the interop surface small — bind `Source` two-way, and the parent
    tab re-renders on change for the dependency preview. The test-harness button
    lives in the parent so one editor can drive multiple script types.
*@

<div class="script-editor">
    <textarea class="form-control font-monospace" rows="14" spellcheck="false"
              @bind="Source" @bind:event="oninput" id="@_editorId">@Source</textarea>
</div>

@code {
    [Parameter] public string Source { get; set; } = string.Empty;
    [Parameter] public EventCallback<string> SourceChanged { get; set; }

    private readonly string _editorId = $"script-editor-{Guid.NewGuid():N}";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                await JS.InvokeVoidAsync("otOpcUaScriptEditor.attach", _editorId);
            }
            catch (JSException)
            {
                // Monaco bundle not yet loaded on this page — textarea fallback is
                // still functional.
            }
        }
    }
}
