@using System
@using System.Collections.Generic
@using System.Linq
@using System.Text.Json
@using RolemasterDb.App.Domain
@using RolemasterDb.App.Features

<div class="critical-diagnostics-body">
    <div class="critical-editor-card nested">
        <div class="critical-editor-card-header">
            <div>
                <strong>Cell Context</strong>
                <p class="muted critical-editor-inline-copy">Engineering metadata for the selected critical-table result.</p>
            </div>
        </div>

        <dl class="critical-editor-diagnostic-grid">
            <div>
                <dt>Result ID</dt>
                <dd>@Model.ResultId</dd>
            </div>
            <div>
                <dt>Table</dt>
                <dd>@Model.TableName</dd>
            </div>
            <div>
                <dt>Source Document</dt>
                <dd>@Model.SourceDocument</dd>
            </div>
            <div>
                <dt>Roll Band</dt>
                <dd>@Model.RollBand</dd>
            </div>
            <div>
                <dt>Severity</dt>
                <dd>@Model.ColumnLabel</dd>
            </div>
            <div>
                <dt>Variant</dt>
                <dd>@(string.IsNullOrWhiteSpace(Model.GroupLabel) ? "—" : Model.GroupLabel)</dd>
            </div>
        </dl>
    </div>

    <div class="critical-editor-card nested">
        <div class="critical-editor-card-header">
            <div>
                <strong>Parser Metadata</strong>
                <p class="muted critical-editor-inline-copy">Last loaded or re-parsed parser result for this cell.</p>
            </div>
        </div>

        <dl class="critical-editor-diagnostic-grid">
            <div>
                <dt>Parse Status</dt>
                <dd>@Model.ParseStatus</dd>
            </div>
            <div>
                <dt>Raw Affix Text</dt>
                <dd>@(string.IsNullOrWhiteSpace(Model.RawAffixText) ? "—" : Model.RawAffixText)</dd>
            </div>
        </dl>

        <div class="field-shell">
            <label>Quick Parse Input</label>
            <pre class="critical-editor-diagnostic-block">@FormatTextBlock(Model.QuickParseInput)</pre>
        </div>

        <div class="field-shell">
            <label>OCR Source</label>
            <pre class="critical-editor-diagnostic-block">@FormatTextBlock(Model.RawCellText)</pre>
        </div>

        @if (Model.ValidationMessages.Count > 0)
        {
            <div class="critical-editor-validation-list">
                @foreach (var message in Model.ValidationMessages)
                {
                    <p class="critical-editor-validation-item">@message</p>
                }
            </div>
        }

        <div class="field-shell">
            <label>Parsed Effects JSON</label>
            <pre class="critical-editor-diagnostic-block">@FormatJson(Model.ParsedJson)</pre>
        </div>
    </div>

    @{
        var effectMetadata = GetEffectMetadataRows(Model);
    }

    @if (effectMetadata.Count > 0)
    {
        <div class="critical-editor-card nested">
            <div class="critical-editor-card-header">
                <div>
                    <strong>Effect Source Metadata</strong>
                    <p class="muted critical-editor-inline-copy">Stored source markers and labels for the current effect list.</p>
                </div>
            </div>

            <div class="critical-editor-diagnostic-list">
                @foreach (var entry in effectMetadata)
                {
                    <div class="critical-editor-diagnostic-item">
                        <div>
                            <strong>@entry.Scope</strong>
                            <p class="muted critical-editor-inline-copy">@entry.EffectLabel</p>
                        </div>
                        <div class="critical-editor-diagnostic-values">
                            <span><strong>Type:</strong> @entry.SourceType</span>
                            <span><strong>Text:</strong> @(string.IsNullOrWhiteSpace(entry.SourceText) ? "—" : entry.SourceText)</span>
                        </div>
                    </div>
                }
            </div>
        </div>
    }

    <div class="critical-editor-card nested">
        <div class="critical-editor-card-header">
            <div>
                <strong>Current Save Payload</strong>
                <p class="muted critical-editor-inline-copy">Request built from the current editor state, including generated branch internals.</p>
            </div>
        </div>
        <pre class="critical-editor-diagnostic-block">@BuildCurrentSavePayloadJson(Model)</pre>
    </div>
</div>

@code {
    [Parameter, EditorRequired]
    public CriticalCellEditorModel Model { get; set; } = default!;

    private static readonly JsonSerializerOptions DiagnosticJsonOptions = new()
    {
        WriteIndented = true
    };

    private static string FormatTextBlock(string? value) =>
        string.IsNullOrWhiteSpace(value) ? "—" : value.Trim();

    private static string FormatJson(string json)
    {
        if (string.IsNullOrWhiteSpace(json))
        {
            return "{}";
        }

        try
        {
            using var document = JsonDocument.Parse(json);
            return JsonSerializer.Serialize(document.RootElement, DiagnosticJsonOptions);
        }
        catch (JsonException)
        {
            return json.Trim();
        }
    }

    private static string BuildCurrentSavePayloadJson(CriticalCellEditorModel model) =>
        JsonSerializer.Serialize(model.ToRequest(), DiagnosticJsonOptions);

    private static List<(string Scope, string EffectLabel, string SourceType, string? SourceText)> GetEffectMetadataRows(CriticalCellEditorModel model)
    {
        var rows = new List<(string Scope, string EffectLabel, string SourceType, string? SourceText)>();

        foreach (var effect in model.Effects)
        {
            if (ShouldIncludeEffectMetadata(effect))
            {
                rows.Add(("Base Result", GetEffectLabel(effect), effect.SourceType, effect.SourceText));
            }
        }

        foreach (var branch in model.Branches.OrderBy(item => item.SortOrder))
        {
            var scope = string.IsNullOrWhiteSpace(branch.ConditionText) ? "Condition" : branch.ConditionText.Trim();
            foreach (var effect in branch.Effects)
            {
                if (ShouldIncludeEffectMetadata(effect))
                {
                    rows.Add((scope, GetEffectLabel(effect), effect.SourceType, effect.SourceText));
                }
            }
        }

        return rows;
    }

    private static bool ShouldIncludeEffectMetadata(CriticalEffectEditorModel effect) =>
        !string.IsNullOrWhiteSpace(effect.SourceText) ||
        !string.IsNullOrWhiteSpace(effect.SourceType);

    private static string GetEffectLabel(CriticalEffectEditorModel effect)
    {
        if (AffixDisplayMap.TryGet(effect.EffectCode, out var info))
        {
            return info.Label;
        }

        return string.IsNullOrWhiteSpace(effect.EffectCode) ? "Custom Effect" : effect.EffectCode;
    }
}
