@php
    use App\Support\Badges\BadgeCatalog;
    use App\Support\Badges\BadgeDomain;

    $resolvedState = isset($getState) ? $getState() : ($artifactTruthState ?? ($state ?? null));
    $state = is_array($resolvedState) ? $resolvedState : [];
    $dimensions = collect(is_array($state['dimensions'] ?? null) ? $state['dimensions'] : []);
    $compressedOutcome = is_array($state['compressedOutcome'] ?? null) ? $state['compressedOutcome'] : [];
    $reason = is_array($state['reason'] ?? null) ? $state['reason'] : [];
    $nextSteps = is_array($reason['nextSteps'] ?? null) ? $reason['nextSteps'] : [];
    $operatorExplanation = is_array($state['operatorExplanation'] ?? null) ? $state['operatorExplanation'] : [];
    $surface = is_string($surface ?? null) && trim($surface) !== '' ? trim($surface) : 'summary';

    $normalizeArtifactTruthText = static function (mixed $value): ?string {
        if (! is_string($value)) {
            return null;
        }

        $value = trim((string) preg_replace('/\s+/', ' ', $value));

        return $value !== '' ? $value : null;
    };

    $firstArtifactTruthText = static function (array $values) use ($normalizeArtifactTruthText): ?string {
        foreach ($values as $value) {
            $normalized = $normalizeArtifactTruthText($value);

            if ($normalized !== null) {
                return $normalized;
            }
        }

        return null;
    };

    $primaryLabel = $firstArtifactTruthText([
        $compressedOutcome['primaryLabel'] ?? null,
        $state['primaryLabel'] ?? null,
        $operatorExplanation['headline'] ?? null,
        __('localization.review.artifact_truth'),
    ]);
    $primaryReason = $firstArtifactTruthText([
        $compressedOutcome['primaryReason'] ?? null,
        data_get($operatorExplanation, 'dominantCause.explanation'),
        $operatorExplanation['reliabilityStatement'] ?? null,
        $state['primaryExplanation'] ?? null,
    ]);
    $nextActionText = $firstArtifactTruthText([
        $compressedOutcome['nextActionText'] ?? null,
        data_get($operatorExplanation, 'nextAction.text'),
        $state['nextActionLabel'] ?? null,
        __('localization.review.no_action_needed'),
    ]);
    $diagnosticsSummary = $firstArtifactTruthText([
        $compressedOutcome['diagnosticsSummary'] ?? null,
        $operatorExplanation['diagnosticsSummary'] ?? null,
        $state['diagnosticLabel'] ?? null,
    ]);

    $primary = $dimensions->first(fn (mixed $dimension): bool => is_array($dimension) && ($dimension['classification'] ?? null) === 'primary');
    $primaryBadge = is_array($compressedOutcome['primaryBadge'] ?? null)
        ? $compressedOutcome['primaryBadge']
        : null;

    if ($primaryBadge === null && is_array($primary)) {
        if (is_string($primary['badgeDomain'] ?? null) && is_string($primary['badgeState'] ?? null)) {
            $primarySpec = BadgeCatalog::spec(BadgeDomain::from($primary['badgeDomain']), $primary['badgeState']);
            $primaryBadge = BadgeCatalog::summaryData($primarySpec);
        }
    }

    $evaluationSpec = is_string($operatorExplanation['evaluationResult'] ?? null)
        ? BadgeCatalog::spec(BadgeDomain::OperatorExplanationEvaluationResult, $operatorExplanation['evaluationResult'])
        : null;
    $trustSpec = is_string($operatorExplanation['trustworthinessLevel'] ?? null)
        ? BadgeCatalog::spec(BadgeDomain::OperatorExplanationTrustworthiness, $operatorExplanation['trustworthinessLevel'])
        : null;
    $operatorCounts = collect(is_array($operatorExplanation['countDescriptors'] ?? null) ? $operatorExplanation['countDescriptors'] : []);
    $displayReference = $normalizeArtifactTruthText($state['displayReference'] ?? null);
    $lifecycleState = $normalizeArtifactTruthText($state['lifecycleState'] ?? null);
    $retentionState = $normalizeArtifactTruthText($state['retentionState'] ?? null);

    $badgeSummaryFact = static function (string $label, BadgeDomain $domain, ?string $state) use ($normalizeArtifactTruthText): ?array {
        $normalizedState = $normalizeArtifactTruthText($state);

        if ($normalizedState === null) {
            return null;
        }

        $spec = BadgeCatalog::spec($domain, $normalizedState);

        if ($spec->label === 'Unknown') {
            return null;
        }

        return [
            'label' => $label,
            'value' => $spec->label,
            'badge' => BadgeCatalog::summaryData($spec),
        ];
    };

    $summaryFacts = collect();

    if ($displayReference !== null) {
        $summaryFacts->push([
            'label' => 'Artifact reference',
            'value' => $displayReference,
            'badge' => null,
        ]);
    }

    $lifecycleFact = $badgeSummaryFact('Lifecycle', BadgeDomain::GovernanceArtifactLifecycle, $lifecycleState);

    if (is_array($lifecycleFact)) {
        $summaryFacts->push($lifecycleFact);
    }

    $retentionFact = $badgeSummaryFact('Retention', BadgeDomain::GovernanceArtifactRetention, $retentionState);

    if (is_array($retentionFact)) {
        $summaryFacts->push($retentionFact);
    }

    if ($evaluationSpec && $evaluationSpec->label !== 'Unknown') {
        $summaryFacts->push([
            'label' => __('localization.review.result_meaning'),
            'value' => $evaluationSpec->label,
            'badge' => BadgeCatalog::summaryData($evaluationSpec),
        ]);
    }

    if ($trustSpec && $trustSpec->label !== 'Unknown') {
        $summaryFacts->push([
            'label' => __('localization.review.result_trust'),
            'value' => $trustSpec->label,
            'badge' => BadgeCatalog::summaryData($trustSpec),
        ]);
    }

    foreach (is_array($compressedOutcome['secondaryFacts'] ?? null) ? $compressedOutcome['secondaryFacts'] : [] as $fact) {
        if (! is_array($fact) || ! is_string($fact['label'] ?? null) || ! is_string($fact['value'] ?? null)) {
            continue;
        }

        $summaryFacts->push([
            'label' => $fact['label'],
            'value' => $fact['value'],
            'badge' => is_array($fact['badge'] ?? null) ? $fact['badge'] : null,
        ]);
    }
@endphp

@if ($surface === 'expanded')
    <div class="space-y-4">
        @if ($summaryFacts->isNotEmpty())
            <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                @foreach ($summaryFacts as $fact)
                    <div class="rounded-md border border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800 dark:bg-gray-950/60">
                        <div class="text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
                            {{ $fact['label'] }}
                        </div>
                        <div class="mt-1">
                            @if (is_array($fact['badge'] ?? null))
                                <x-filament::badge :color="$fact['badge']['color'] ?? 'gray'" :icon="$fact['badge']['icon'] ?? null" size="sm">
                                    {{ $fact['value'] }}
                                </x-filament::badge>
                            @else
                                <span class="text-sm text-gray-900 dark:text-gray-100">{{ $fact['value'] }}</span>
                            @endif
                        </div>
                    </div>
                @endforeach
            </div>
        @endif

        <div class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
            <div class="text-xs font-semibold uppercase tracking-[0.16em] text-gray-500 dark:text-gray-400">
                {{ __('localization.review.diagnostics') }}
            </div>

            <div class="mt-3 space-y-2">
                @if ($primaryReason !== null && $compressedOutcome === [])
                    <p class="text-sm text-gray-700 dark:text-gray-200">
                        {{ $primaryReason }}
                    </p>
                @endif

                @if (is_string($operatorExplanation['coverageStatement'] ?? null) && trim($operatorExplanation['coverageStatement']) !== '')
                    <p class="text-sm text-gray-600 dark:text-gray-300">
                        {{ $operatorExplanation['coverageStatement'] }}
                    </p>
                @endif

                @if ($diagnosticsSummary !== null)
                    <p class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">
                        {{ $diagnosticsSummary }}
                    </p>
                @endif
            </div>
        </div>

        @if ($operatorCounts->isNotEmpty())
            <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                @foreach ($operatorCounts as $count)
                    @continue(! is_array($count))

                    <div class="rounded-md border border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800 dark:bg-gray-950/60">
                        <div class="text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
                            {{ $count['label'] ?? __('localization.review.count') }}
                        </div>
                        <div class="mt-1 text-lg font-semibold text-gray-900 dark:text-gray-100">
                            {{ (int) ($count['value'] ?? 0) }}
                        </div>
                        @if (filled($count['qualifier'] ?? null))
                            <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                {{ $count['qualifier'] }}
                            </div>
                        @endif
                    </div>
                @endforeach
            </div>
        @endif
    </div>
@else
    <div class="space-y-4">
        <div class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
            @if (is_array($primaryBadge))
                <div class="flex flex-wrap items-start gap-2">
                    <x-filament::badge :color="$primaryBadge['color'] ?? 'gray'" :icon="$primaryBadge['icon'] ?? null" size="sm">
                        {{ $primaryBadge['label'] ?? $primaryLabel }}
                    </x-filament::badge>
                </div>
            @endif

            <div class="mt-3 space-y-2">
                <div class="text-sm font-medium text-gray-950 dark:text-gray-100">
                    {{ $primaryLabel }}
                </div>

                @if ($primaryReason !== null)
                    <p class="text-sm text-gray-600 dark:text-gray-300">
                        {{ $primaryReason }}
                    </p>
                @endif

                @if ($diagnosticsSummary !== null)
                    <p class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">
                        {{ $diagnosticsSummary }}
                    </p>
                @endif
            </div>
        </div>

        <dl class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
            <div class="rounded-md border border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800 dark:bg-gray-950/60">
                <dt class="text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">{{ __('localization.review.next_step') }}</dt>
                <dd class="mt-1 text-sm text-gray-900 dark:text-gray-100">
                    {{ $nextActionText }}
                </dd>
            </div>

            @foreach ($summaryFacts as $fact)
                <div class="rounded-md border border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800 dark:bg-gray-950/60">
                    <dt class="text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
                        {{ $fact['label'] }}
                    </dt>
                    <dd class="mt-1">
                        @if (is_array($fact['badge'] ?? null))
                            <x-filament::badge :color="$fact['badge']['color'] ?? 'gray'" :icon="$fact['badge']['icon'] ?? null" size="sm">
                                {{ $fact['value'] }}
                            </x-filament::badge>
                        @else
                            <span class="text-sm text-gray-900 dark:text-gray-100">{{ $fact['value'] }}</span>
                        @endif
                    </dd>
                </div>
            @endforeach
        </dl>

        @if ($nextSteps !== [])
            <div class="space-y-2">
                <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">{{ __('localization.review.guidance') }}</div>
                <ul class="space-y-1 text-sm text-gray-700 dark:text-gray-300">
                    @foreach ($nextSteps as $step)
                        @continue(! is_string($step) || trim($step) === '')

                        <li class="rounded-md border border-primary-100 bg-primary-50 px-3 py-2 dark:border-primary-900/40 dark:bg-primary-950/30">
                            {{ $step }}
                        </li>
                    @endforeach
                </ul>
            </div>
        @endif
    </div>
@endif
