@namespace ScadaLink.CentralUI.Components.Shared
@using ScadaLink.CentralUI.ScriptAnalysis

@if (Markers.Count > 0)
{
    <div class="card mt-2 mb-3">
        <div class="card-header py-1 small d-flex justify-content-between align-items-center">
            <span>
                @if (_errorCount > 0)
                {
                    <span class="badge bg-danger me-1">@_errorCount error@(_errorCount == 1 ? "" : "s")</span>
                }
                @if (_warningCount > 0)
                {
                    <span class="badge bg-warning text-dark me-1">@_warningCount warning@(_warningCount == 1 ? "" : "s")</span>
                }
                @if (_infoCount > 0)
                {
                    <span class="badge bg-info text-dark me-1">@_infoCount info</span>
                }
            </span>
            <span class="text-muted">Problems</span>
        </div>
        <ul class="list-unstyled mb-0 small" style="max-height: 180px; overflow-y: auto;">
            @foreach (var m in Markers)
            {
                <li class="d-flex gap-2 align-items-start px-2 py-1 border-bottom">
                    <span class="badge @SeverityBadge(m.Severity)" style="min-width: 60px;">@SeverityLabel(m.Severity)</span>
                    <button type="button" class="btn btn-link btn-sm p-0 text-decoration-none flex-grow-1 text-start"
                            @onclick="@(() => OnNavigate.InvokeAsync(m))">
                        <span class="text-muted me-2">Line @m.StartLineNumber</span>@m.Message
                    </button>
                    <code class="text-muted small">@m.Code</code>
                </li>
            }
        </ul>
    </div>
}

@code {
    [Parameter, EditorRequired] public IReadOnlyList<DiagnosticMarker> Markers { get; set; } = Array.Empty<DiagnosticMarker>();
    [Parameter] public EventCallback<DiagnosticMarker> OnNavigate { get; set; }

    private int _errorCount;
    private int _warningCount;
    private int _infoCount;

    protected override void OnParametersSet()
    {
        _errorCount = Markers.Count(m => m.Severity >= 8);
        _warningCount = Markers.Count(m => m.Severity == 4);
        _infoCount = Markers.Count(m => m.Severity > 0 && m.Severity < 4);
    }

    private static string SeverityBadge(int sev) => sev switch
    {
        >= 8 => "bg-danger",
        4 => "bg-warning text-dark",
        _ => "bg-info text-dark"
    };

    private static string SeverityLabel(int sev) => sev switch
    {
        >= 8 => "Error",
        4 => "Warning",
        _ => "Info"
    };
}
