@php
    $fieldWrapperView = $getFieldWrapperView();

    $diffs = $getState() ?? [];
    $diffs = is_array($diffs) ? $diffs : [];

    $summary = $summary ?? [];
    $summary = is_array($summary) ? $summary : [];

    $previewIntegrity = $previewIntegrity ?? [];
    $previewIntegrity = is_array($previewIntegrity) ? $previewIntegrity : [];

    $checksIntegrity = $checksIntegrity ?? [];
    $checksIntegrity = is_array($checksIntegrity) ? $checksIntegrity : [];

    $safetyAssessment = $safetyAssessment ?? [];
    $safetyAssessment = is_array($safetyAssessment) ? $safetyAssessment : [];

    $ranAt = $ranAt ?? ($previewIntegrity['generated_at'] ?? null);
    $ranAtLabel = null;

    if (is_string($ranAt) && $ranAt !== '') {
        try {
            $ranAtLabel = \Carbon\CarbonImmutable::parse($ranAt)->format('Y-m-d H:i');
        } catch (\Throwable) {
            $ranAtLabel = $ranAt;
        }
    }

    $integritySpec = \App\Support\Badges\BadgeRenderer::spec(
        \App\Support\Badges\BadgeDomain::RestorePreviewDecision,
        $previewIntegrity['state'] ?? 'not_generated'
    );

    $policiesTotal = (int) ($summary['policies_total'] ?? 0);
    $policiesChanged = (int) ($summary['policies_changed'] ?? 0);
    $assignmentsChanged = (int) ($summary['assignments_changed'] ?? 0);
    $scopeTagsChanged = (int) ($summary['scope_tags_changed'] ?? 0);
    $diffsOmitted = (int) ($summary['diffs_omitted'] ?? 0);
    $integritySummary = $previewIntegrity['display_summary'] ?? 'Generate a preview before real execution.';
    $nextAction = $safetyAssessment['primary_next_action'] ?? 'generate_preview';
    $nextActionLabel = \App\Support\RestoreSafety\RestoreSafetyCopy::primaryNextAction(is_string($nextAction) ? $nextAction : 'generate_preview');
    $limitedKeys = static function (array $items, int $limit = 8): array {
        $keys = array_keys($items);

        if (count($keys) <= $limit) {
            return $keys;
        }

        return array_slice($keys, 0, $limit);
    };
@endphp

<x-dynamic-component :component="$fieldWrapperView" :field="$field">
    <div class="space-y-4">
        <x-filament::section
            heading="Preview"
            :description="$ranAtLabel ? ('Generated: ' . $ranAtLabel) : 'Preview answers what would change for the current scope.'"
        >
            <div class="space-y-3">
                <div class="flex flex-wrap gap-2">
                    <x-filament::badge :color="$integritySpec->color" :icon="$integritySpec->icon" size="sm">
                        {{ $integritySpec->label }}
                    </x-filament::badge>
                    @if (($checksIntegrity['state'] ?? null) === 'current')
                        <x-filament::badge color="success" size="sm">
                            Checks current
                        </x-filament::badge>
                    @endif
                    @if (($safetyAssessment['state'] ?? null) === 'ready_with_caution')
                        <x-filament::badge color="warning" size="sm">
                            Calm readiness suppressed
                        </x-filament::badge>
                    @endif
                </div>

                <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-3 text-sm text-slate-900 dark:border-white/10 dark:bg-white/5 dark:text-slate-100">
                    <div class="font-medium">What the preview proves</div>
                    <div class="mt-1">{{ $integritySummary }}</div>
                    <div class="mt-2 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:text-slate-400">
                        Primary next step
                    </div>
                    <div class="mt-1 text-xs text-slate-600 dark:text-slate-300">
                        {{ $nextActionLabel }}
                    </div>
                </div>

                <div class="flex flex-wrap gap-2">
                    <x-filament::badge :color="$policiesChanged > 0 ? 'warning' : 'success'">
                        {{ $policiesChanged }}/{{ $policiesTotal }} policies changed
                    </x-filament::badge>
                    <x-filament::badge :color="$assignmentsChanged > 0 ? 'warning' : 'gray'">
                        {{ $assignmentsChanged }} assignments changed
                    </x-filament::badge>
                    <x-filament::badge :color="$scopeTagsChanged > 0 ? 'warning' : 'gray'">
                        {{ $scopeTagsChanged }} scope tags changed
                    </x-filament::badge>
                    @if ($diffsOmitted > 0)
                        <x-filament::badge color="gray">
                            {{ $diffsOmitted }} diffs omitted (limit)
                        </x-filament::badge>
                    @endif
                </div>

                @if (($previewIntegrity['invalidation_reasons'] ?? []) !== [])
                    <div class="text-xs text-amber-800 dark:text-amber-200">
                        Invalidated by: {{ implode(', ', array_map(static fn (string $reason): string => \Illuminate\Support\Str::replace('_', ' ', $reason), $previewIntegrity['invalidation_reasons'])) }}
                    </div>
                @endif
            </div>
        </x-filament::section>

        @if ($diffs === [])
            <x-filament::section>
                <div class="text-sm text-gray-600 dark:text-gray-300">
                    No preview diff is recorded for this scope yet.
                </div>
            </x-filament::section>
        @else
            <div class="space-y-3">
                @foreach ($diffs as $entry)
                    @php
                        $entry = is_array($entry) ? $entry : [];
                        $name = $entry['display_name'] ?? $entry['policy_identifier'] ?? 'Item';
                        $type = $entry['policy_type'] ?? 'type';
                        $platform = $entry['platform'] ?? 'platform';
                        $action = $entry['action'] ?? 'update';
                        $diff = is_array($entry['diff'] ?? null) ? $entry['diff'] : [];
                        $diffSummary = is_array($diff['summary'] ?? null) ? $diff['summary'] : [];
                        $added = (int) ($diffSummary['added'] ?? 0);
                        $removed = (int) ($diffSummary['removed'] ?? 0);
                        $changed = (int) ($diffSummary['changed'] ?? 0);
                        $assignmentsDelta = (bool) ($entry['assignments_changed'] ?? false);
                        $scopeTagsDelta = (bool) ($entry['scope_tags_changed'] ?? false);
                        $diffOmitted = (bool) ($entry['diff_omitted'] ?? false);
                        $diffTruncated = (bool) ($entry['diff_truncated'] ?? false);
                        $changedKeys = $limitedKeys(is_array($diff['changed'] ?? null) ? $diff['changed'] : []);
                        $addedKeys = $limitedKeys(is_array($diff['added'] ?? null) ? $diff['added'] : []);
                        $removedKeys = $limitedKeys(is_array($diff['removed'] ?? null) ? $diff['removed'] : []);
                    @endphp

                    <x-filament::section :heading="$name" :description="sprintf('%s • %s', $type, $platform)" collapsible :collapsed="true">
                        <div class="flex flex-wrap gap-2">
                            <x-filament::badge :color="$action === 'create' ? 'success' : 'gray'" size="sm">
                                {{ $action }}
                            </x-filament::badge>
                            <x-filament::badge color="success" size="sm">
                                {{ $added }} added
                            </x-filament::badge>
                            <x-filament::badge color="danger" size="sm">
                                {{ $removed }} removed
                            </x-filament::badge>
                            <x-filament::badge color="warning" size="sm">
                                {{ $changed }} changed
                            </x-filament::badge>
                            @if ($assignmentsDelta)
                                <x-filament::badge color="warning" size="sm">
                                    assignments
                                </x-filament::badge>
                            @endif
                            @if ($scopeTagsDelta)
                                <x-filament::badge color="warning" size="sm">
                                    scope tags
                                </x-filament::badge>
                            @endif
                            @if ($diffTruncated)
                                <x-filament::badge color="gray" size="sm">
                                    truncated
                                </x-filament::badge>
                            @endif
                        </div>

                        @if ($diffOmitted)
                            <div class="mt-3 text-sm text-gray-600 dark:text-gray-300">
                                Diff details omitted due to preview limits. Narrow scope to see more items in detail.
                            </div>
                        @elseif ($changedKeys !== [] || $addedKeys !== [] || $removedKeys !== [])
                            <div class="mt-3 space-y-3 text-sm text-gray-700 dark:text-gray-200">
                                @if ($changedKeys !== [])
                                    <div>
                                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
                                            Changed keys (sample)
                                        </div>
                                        <ul class="mt-1 space-y-1">
                                            @foreach ($changedKeys as $key)
                                                <li class="rounded bg-gray-50 px-2 py-1 text-xs text-gray-800 dark:bg-white/5 dark:text-gray-200">
                                                    {{ $key }}
                                                </li>
                                            @endforeach
                                        </ul>
                                    </div>
                                @endif
                                @if ($addedKeys !== [])
                                    <div>
                                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
                                            Added keys (sample)
                                        </div>
                                        <ul class="mt-1 space-y-1">
                                            @foreach ($addedKeys as $key)
                                                <li class="rounded bg-gray-50 px-2 py-1 text-xs text-gray-800 dark:bg-white/5 dark:text-gray-200">
                                                    {{ $key }}
                                                </li>
                                            @endforeach
                                        </ul>
                                    </div>
                                @endif
                                @if ($removedKeys !== [])
                                    <div>
                                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
                                            Removed keys (sample)
                                        </div>
                                        <ul class="mt-1 space-y-1">
                                            @foreach ($removedKeys as $key)
                                                <li class="rounded bg-gray-50 px-2 py-1 text-xs text-gray-800 dark:bg-white/5 dark:text-gray-200">
                                                    {{ $key }}
                                                </li>
                                            @endforeach
                                        </ul>
                                    </div>
                                @endif
                            </div>
                        @endif
                    </x-filament::section>
                @endforeach
            </div>
        @endif
    </div>
</x-dynamic-component>
