@php
    use App\Support\Badges\BadgeCatalog;
    use App\Support\Badges\BadgeDomain;
    use App\Support\Badges\BadgeSpec;
    use Illuminate\Support\Str;

    $blocks = is_array($blocks ?? null) ? $blocks : [];
    $policyType = is_string($policyType ?? null) ? $policyType : null;

    $stringifyValue = function (mixed $value): string {
        if (is_null($value)) {
            return 'N/A';
        }

        if (is_bool($value)) {
            return $value ? 'Enabled' : 'Disabled';
        }

        if (is_scalar($value)) {
            return (string) $value;
        }

        if (is_array($value)) {
            $encoded = json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

            return is_string($encoded) ? $encoded : 'N/A';
        }

        if (is_object($value)) {
            if (method_exists($value, '__toString')) {
                return (string) $value;
            }

            $encoded = json_encode((array) $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

            return is_string($encoded) ? $encoded : 'N/A';
        }

        return 'N/A';
    };

    $shouldRenderBadges = function (mixed $value): bool {
        if (! is_array($value) || $value === []) {
            return false;
        }

        if (! array_is_list($value)) {
            return false;
        }

        foreach ($value as $item) {
            if (! is_scalar($item) && ! is_null($item)) {
                return false;
            }
        }

        return true;
    };

    $asEnabledDisabledBadgeSpec = function (mixed $value): ?BadgeSpec {
        $spec = BadgeCatalog::spec(BadgeDomain::BooleanEnabled, $value);

        return $spec->label === 'Unknown' ? null : $spec;
    };
@endphp

<div class="space-y-4" data-shared-zone="blocks">
    @foreach ($blocks as $block)
        @php
            $blockType = is_array($block) ? ($block['type'] ?? null) : null;
        @endphp

        @if ($blockType === 'table')
            <x-filament::section
                :heading="$block['title'] ?? 'Settings'"
                collapsible
            >
                <x-slot name="headerEnd">
                    <span class="text-sm text-gray-500 dark:text-gray-400">
                        {{ count($block['rows'] ?? []) }} {{ Str::plural('item', count($block['rows'] ?? [])) }}
                    </span>
                </x-slot>

                <div class="divide-y divide-gray-200 dark:divide-gray-700">
                    @foreach ($block['rows'] ?? [] as $row)
                        <div class="py-3 sm:grid sm:grid-cols-3 sm:gap-4">
                            <dt class="text-sm font-medium text-gray-500 dark:text-gray-400 break-words">
                                {{ $row['label'] ?? $row['path'] ?? 'Setting' }}

                                @if (! empty($row['path']) && ($row['label'] ?? null) !== ($row['path'] ?? null))
                                    <p class="mt-0.5 break-all text-xs font-mono text-gray-400 dark:text-gray-500">
                                        {{ (string) $row['path'] }}
                                    </p>
                                @endif

                                @if (! empty($row['description']))
                                    <p class="mt-0.5 text-xs text-gray-400">{{ Str::limit($row['description'], 80) }}</p>
                                @endif
                            </dt>
                            <dd class="mt-1 sm:col-span-2 sm:mt-0">
                                @php
                                    $badgeSpec = $asEnabledDisabledBadgeSpec($row['value'] ?? null);
                                @endphp

                                @if ($badgeSpec)
                                    <x-filament::badge :color="$badgeSpec->color" :icon="$badgeSpec->icon" size="sm">
                                        {{ $badgeSpec->label }}
                                    </x-filament::badge>
                                @elseif (is_numeric($row['value'] ?? null))
                                    <span class="font-mono text-sm font-semibold text-gray-900 dark:text-white">
                                        {{ $row['value'] }}
                                    </span>
                                @elseif ($shouldRenderBadges($row['value'] ?? null))
                                    <div class="flex flex-wrap gap-1.5">
                                        @foreach (($row['value'] ?? []) as $item)
                                            @php
                                                $itemSpec = $asEnabledDisabledBadgeSpec($item);
                                            @endphp

                                            @if ($itemSpec)
                                                <x-filament::badge :color="$itemSpec->color" :icon="$itemSpec->icon" size="sm">
                                                    {{ $itemSpec->label }}
                                                </x-filament::badge>
                                            @else
                                                <x-filament::badge color="gray" size="sm">
                                                    {{ is_null($item) ? '—' : (string) $item }}
                                                </x-filament::badge>
                                            @endif
                                        @endforeach
                                    </div>
                                @else
                                    <span class="break-words text-sm text-gray-900 dark:text-white">
                                        {{ Str::limit($stringifyValue($row['value'] ?? null), 200) }}
                                    </span>
                                @endif
                            </dd>
                        </div>
                    @endforeach
                </div>
            </x-filament::section>
        @elseif ($blockType === 'keyValue')
            <x-filament::section
                :heading="$block['title'] ?? 'Settings'"
                collapsible
            >
                <x-slot name="headerEnd">
                    <span class="text-sm text-gray-500 dark:text-gray-400">
                        {{ count($block['entries'] ?? []) }} {{ Str::plural('entry', count($block['entries'] ?? [])) }}
                    </span>
                </x-slot>

                <div class="divide-y divide-gray-200 dark:divide-gray-700">
                    @foreach ($block['entries'] ?? [] as $entry)
                        <div class="py-3 sm:grid sm:grid-cols-3 sm:gap-4">
                            <dt class="text-sm font-medium text-gray-500 dark:text-gray-400">
                                {{ $entry['key'] ?? 'Setting' }}
                            </dt>
                            <dd class="mt-1 sm:col-span-2 sm:mt-0">
                                @php
                                    $rawValue = $entry['value'] ?? null;
                                    $isScriptContent = in_array($entry['key'] ?? null, ['scriptContent', 'detectionScriptContent', 'remediationScriptContent'], true)
                                        && (bool) config('tenantpilot.display.show_script_content', false);
                                    $badgeSpec = $asEnabledDisabledBadgeSpec($rawValue);
                                @endphp

                                @if ($isScriptContent)
                                    @php
                                        $code = is_string($rawValue) ? $rawValue : $stringifyValue($rawValue);
                                        $firstLine = strtok($code, "\n") ?: '';
                                        $grammar = 'powershell';

                                        if ($policyType === 'deviceShellScript') {
                                            $shebang = trim($firstLine);

                                            if (str_starts_with($shebang, '#!')) {
                                                if (str_contains($shebang, 'zsh')) {
                                                    $grammar = 'zsh';
                                                } elseif (str_contains($shebang, 'bash')) {
                                                    $grammar = 'bash';
                                                } else {
                                                    $grammar = 'sh';
                                                }
                                            } else {
                                                $grammar = 'sh';
                                            }
                                        } elseif ($policyType === 'deviceManagementScript' || $policyType === 'deviceHealthScript') {
                                            $grammar = 'powershell';
                                        }

                                        $highlightedHtml = null;

                                        if (class_exists(\Torchlight\Engine\Engine::class)) {
                                            try {
                                                $highlightedHtml = (new \Torchlight\Engine\Engine())->codeToHtml(
                                                    code: $code,
                                                    grammar: $grammar,
                                                    theme: [
                                                        'light' => 'github-light',
                                                        'dark' => 'github-dark',
                                                    ],
                                                    withGutter: false,
                                                    withWrapper: true,
                                                );
                                            } catch (\Throwable $e) {
                                                $highlightedHtml = null;
                                            }
                                        }
                                    @endphp

                                    <div x-data="{ open: false }" class="space-y-2">
                                        <div class="flex items-center gap-2">
                                            <x-filament::button
                                                size="xs"
                                                color="gray"
                                                type="button"
                                                x-on:click="open = !open"
                                            >
                                                <span x-cloak x-show="!open">Show</span>
                                                <span x-cloak x-show="open">Hide</span>
                                            </x-filament::button>

                                            <span class="text-xs text-gray-500 dark:text-gray-400">
                                                {{ number_format(Str::length($code)) }} chars
                                            </span>
                                        </div>

                                        <div x-cloak x-show="open">
                                            @if (is_string($highlightedHtml) && $highlightedHtml !== '')
                                                @once
                                                    @include('filament.partials.torchlight-dark-overrides')
                                                @endonce

                                                <div class="overflow-x-auto">{!! $highlightedHtml !!}</div>
                                            @else
                                                <pre class="whitespace-pre-wrap break-words text-xs font-mono text-gray-900 dark:text-white">{{ $code }}</pre>
                                            @endif
                                        </div>
                                    </div>
                                @elseif ($shouldRenderBadges($rawValue))
                                    <div class="flex flex-wrap gap-1.5">
                                        @foreach (($rawValue ?? []) as $item)
                                            @php
                                                $itemSpec = $asEnabledDisabledBadgeSpec($item);
                                            @endphp

                                            @if ($itemSpec)
                                                <x-filament::badge :color="$itemSpec->color" :icon="$itemSpec->icon" size="sm">
                                                    {{ $itemSpec->label }}
                                                </x-filament::badge>
                                            @else
                                                <x-filament::badge color="gray" size="sm">
                                                    {{ is_null($item) ? '—' : (string) $item }}
                                                </x-filament::badge>
                                            @endif
                                        @endforeach
                                    </div>
                                @elseif ($badgeSpec)
                                    <x-filament::badge :color="$badgeSpec->color" :icon="$badgeSpec->icon" size="sm">
                                        {{ $badgeSpec->label }}
                                    </x-filament::badge>
                                @else
                                    <span class="break-words text-sm text-gray-900 dark:text-white">
                                        {{ Str::limit($stringifyValue($rawValue), 200) }}
                                    </span>
                                @endif
                            </dd>
                        </div>
                    @endforeach
                </div>
            </x-filament::section>
        @endif
    @endforeach
</div>