@* Embeddable Modbus device (connection endpoint) form body — authors Host/Port/UnitId into the
   Device's DeviceConfig (PascalCase, matching ModbusDriverOptions). Hosted by DeviceModal. *@
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.DeviceForms

<section class="panel rise" style="animation-delay:.04s">
    <div class="panel-head">Connection</div>
    <div style="padding:1rem">
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label">Host</label>
                <InputText @bind-Value="_model.Host" @bind-Value:after="EmitAsync" class="form-control form-control-sm mono" placeholder="127.0.0.1" />
            </div>
            <div class="col-md-3">
                <label class="form-label">Port</label>
                <InputNumber @bind-Value="_model.Port" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
            </div>
            <div class="col-md-3">
                <label class="form-label">Unit ID (slave ID)</label>
                <InputNumber @bind-Value="_model.UnitId" @bind-Value:after="EmitAsync" class="form-control form-control-sm" />
            </div>
        </div>
    </div>
</section>

@code {
    /// <summary>The device's DeviceConfig JSON (endpoint/connection keys).</summary>
    [Parameter] public string DeviceConfigJson { get; set; } = "{}";
    /// <summary>Fired (PascalCase Host/Port/UnitId) whenever the endpoint changes — enables @bind-DeviceConfigJson.</summary>
    [Parameter] public EventCallback<string> DeviceConfigJsonChanged { get; set; }

    private ModbusDeviceModel _model = new();
    private string? _lastParsed;

    protected override void OnParametersSet()
    {
        if (!string.Equals(_lastParsed, DeviceConfigJson, StringComparison.Ordinal))
        {
            _model = ModbusDeviceModel.FromJson(DeviceConfigJson);
            _lastParsed = DeviceConfigJson;
        }
    }

    /// <summary>Serializes the current endpoint to DeviceConfig JSON.</summary>
    public string GetConfigJson() => _model.ToJson();

    private async Task EmitAsync()
    {
        var json = GetConfigJson();
        _lastParsed = json;
        await DeviceConfigJsonChanged.InvokeAsync(json);
    }
}
