@php
    /** @var mixed $value */
    $value = $value ?? null;

    $payloadArray = is_string($value)
        ? (json_decode($value, true) ?? [])
        : ($value ?? []);

    $rawJson = json_encode(
        $payloadArray,
        JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
    ) ?: '';
@endphp

<div
    class="space-y-2"
    x-data="{
        open: false,
        text: @js($rawJson),
        copied: false,
        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();
                }

                this.copied = true;
                setTimeout(() => (this.copied = false), 1500);
            } catch (e) {
                this.copied = false;
            }
        },
    }"
>
    <div class="flex items-center justify-end gap-2">
        <span
            x-show="copied"
            x-cloak
            x-transition
            class="text-sm text-gray-500 dark:text-gray-400"
        >
            Copied
        </span>

        <x-filament::button size="xs" color="gray" x-on:click="copyJson()">
            Copy JSON
        </x-filament::button>

        <x-filament::button size="xs" color="gray" x-on:click="open = !open">
            <span x-text="open ? 'Hide JSON' : 'Show JSON'"></span>
        </x-filament::button>
    </div>

    <div x-show="open" x-cloak x-collapse class="rounded-lg border border-gray-200 bg-gray-50 p-3 dark:border-gray-800 dark:bg-gray-900">
        <pre class="max-h-96 overflow-auto whitespace-pre font-mono text-xs text-gray-900 dark:text-gray-100" x-text="text"></pre>
    </div>
</div>
