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

    // Extract groups from Filament ViewEntry state using $getState()
    $groups = [];
    $searchQuery = $searchQuery ?? '';

    // Use $getState() function provided by Filament Entry component
    $state = $getState();
    
    // Handle different types: object, array, string, closure
    if ($state instanceof \Closure) {
        $state = $state(); // Execute closure to get actual data
    }
    
    if (is_object($state)) {
        // Convert stdClass or other objects to array
        $state = json_decode(json_encode($state), true);
    }
    
    if (is_string($state) && Str::startsWith(trim($state), '{')) {
        $state = json_decode($state, true);
    }
    
    if (is_array($state)) {
        $groups = $state['groups'] ?? $state;
    }

    // Ensure groups is always an array
    $groups = is_array($groups) ? $groups : [];
@endphp

<div class="space-y-4">
    @if(empty($groups))
        <div class="text-center py-8">
            <p class="text-gray-500 dark:text-gray-400">No settings available</p>
        </div>
    @else
        @foreach($groups as $groupIndex => $group)
            @php
                // Filter settings by search query
                $filteredSettings = collect($group['settings'] ?? [])->filter(function($setting) use ($searchQuery) {
                    if (empty($searchQuery)) {
                        return true;
                    }
                    
                    $searchLower = strtolower($searchQuery);
                    return str_contains(strtolower($setting['label'] ?? ''), $searchLower) ||
                           str_contains(strtolower($setting['value_display'] ?? ''), $searchLower);
                })->all();
                
                $settingCount = count($filteredSettings);
            @endphp

            @if($settingCount > 0)
                <x-filament::section
                    :heading="$group['title'] ?? 'Settings'"
                    :description="$group['description'] ?? null"
                    collapsible
                    :collapsed="$groupIndex > 0"
                >
                    <x-slot name="headerEnd">
                        <span class="text-sm text-gray-500 dark:text-gray-400">
                            {{ $settingCount }} {{ Str::plural('setting', $settingCount) }}
                        </span>
                    </x-slot>

                    <dl class="divide-y divide-gray-200 dark:divide-gray-700">
                        @foreach($filteredSettings as $setting)
                            <div class="py-3 grid grid-cols-1 md:grid-cols-3 md:gap-4 items-start">
                                <dt class="text-sm font-medium text-gray-500 dark:text-gray-400 break-words">
                                    {{ $setting['label'] }}
                                </dt>
	                                <dd class="mt-1 md:mt-0 md:col-span-2 break-words">
	                                    <div class="flex flex-wrap items-center gap-3">
	                                        @php
	                                            $rawValue = $setting['value_raw'] ?? null;
	                                            $displayValue = $setting['value_display'] ?? null;

	                                            $booleanSpec = BadgeCatalog::spec(BadgeDomain::BooleanEnabled, $rawValue);

	                                            if ($booleanSpec->label === 'Unknown') {
	                                                $booleanSpec = BadgeCatalog::spec(BadgeDomain::BooleanEnabled, $displayValue);
	                                            }

	                                            $hasBooleanBadge = $booleanSpec->label !== 'Unknown';
	                                        @endphp

	                                        @if($hasBooleanBadge)
	                                            <x-filament::badge :color="$booleanSpec->color" :icon="$booleanSpec->icon" size="sm">
	                                                {{ $booleanSpec->label }}
	                                            </x-filament::badge>
	                                        @elseif(is_int($rawValue))
	                                            <span class="font-mono text-sm font-semibold text-gray-900 dark:text-white">
	                                                {{ $displayValue }}
	                                            </span>
	                                        @else
	                                            <span class="text-sm text-gray-900 dark:text-white whitespace-pre-wrap">
	                                                {{ $displayValue }}
	                                            </span>
	                                        @endif

                                        @if(strlen($setting['value_display'] ?? '') > 200)
                                            <button
                                                type="button"
                                                x-data="{ copied: false }"
                                                x-on:click="
                                                    navigator.clipboard.writeText('{{ addslashes($setting['value_display']) }}');
                                                    copied = true;
                                                    setTimeout(() => copied = false, 2000);
                                                "
                                                class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition"
                                                title="Copy value"
                                            >
                                                <svg x-show="!copied" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                                                </svg>
                                                <svg x-show="copied" x-cloak class="w-4 h-4 text-success-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                                </svg>
                                            </button>
                                        @endif
                                    </div>

                                    @if(!empty($setting['help_text']))
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                            {{ Str::limit($setting['help_text'], 150) }}
                                        </p>
                                    @endif
                                </dd>
                            </div>
                        @endforeach
                    </dl>
                </x-filament::section>
            @endif
        @endforeach

        @if(collect($groups)->sum(fn($g) => count(collect($g['settings'] ?? [])->filter(function($s) use ($searchQuery) {
            if (empty($searchQuery)) return true;
            $searchLower = strtolower($searchQuery);
            return str_contains(strtolower($s['label'] ?? ''), $searchLower) ||
                   str_contains(strtolower($s['value_display'] ?? ''), $searchLower);
        }))) === 0)
            <div class="text-center py-8">
                <p class="text-gray-500 dark:text-gray-400">No settings match your search</p>
                <button
                    type="button"
                    wire:click="$set('search', '')"
                    class="mt-2 text-sm text-primary-600 hover:text-primary-700 dark:text-primary-400"
                >
                    Clear search
                </button>
            </div>
        @endif
    @endif
</div>
