@php
    // Obtain state from Filament infolist entry
    $payload = $getState();

    // Normalize payload to array for the JSON viewer
    $payloadArray = is_string($payload) ? (json_decode($payload, true) ?? []) : ($payload ?? []);
    $rawJson = json_encode($payloadArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    // Provide the small set of helpers the pepperfm json view expects
    $getState = fn () => $payloadArray;
    $getCharacterLimit = fn () => null;
    $getAsModal = fn () => false;
    $getAsDrawer = fn () => false;
    $getKeyColumnLabel = fn () => 'Key';
    $getValueColumnLabel = fn () => 'Value';
    $getButtonConfig = fn () => (object) ['id' => 'fj-modal', 'icon' => null, 'iconColor' => null, 'alignment' => null, 'width' => null, 'closeByClickingAway' => true, 'closedByEscaping' => true, 'closedButton' => true, 'label' => null, 'tooltip' => null, 'size' => null, 'href' => null, 'tag' => null, 'color' => null];
    $getModalConfig = fn () => (object) ['id' => 'fj-modal', 'icon' => null, 'iconColor' => null, 'alignment' => null, 'width' => null, 'closeByClickingAway' => true, 'closedByEscaping' => true, 'closedButton' => true];
    $getRenderMode = fn () => \PepperFM\FilamentJson\Enums\RenderModeEnum::Tree;
    $getInitiallyCollapsed = fn () => 1;
    $getExpandAllToggle = fn () => false;
    $getCopyJsonAction = fn () => false;
    $getMaxDepth = fn () => 3;
    $applyLimit = fn ($v) => $v;
@endphp

<div
    class="space-y-2"
    x-data="{
        text: @js($rawJson),
        async copyJson() {
            try {
                if (navigator.clipboard && (location.protocol === 'https:' || location.hostname === 'localhost')) {
                    await navigator.clipboard.writeText(this.text);
                } else {
                    const ta = document.createElement('textarea');
                    ta.value = this.text;
                    ta.style.position = 'fixed';
                    ta.style.inset = '0';
                    document.body.appendChild(ta);
                    ta.focus();
                    ta.select();
                    document.execCommand('copy');
                    ta.remove();
                }

                new FilamentNotification()
                    .title('Copied!')
                    .icon('heroicon-o-clipboard-document-check')
                    .success()
                    .send();
            } catch (e) {
                new FilamentNotification()
                    .title('Copy failed!')
                    .danger()
                    .send();
            }
        }
    }"
>
    <div class="flex items-center justify-end">
        <x-filament::button size="xs" color="gray" x-on:click="copyJson()">
            Copy JSON
        </x-filament::button>
    </div>

    {{-- Render pepperfm filament-json viewer --}}
    @include('filament-json::json')
</div>
