<div>
    {{-- Header --}}
    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4 sm:mb-6">
        <div>
            <h1 class="text-xl sm:text-2xl font-bold text-gray-800">{{ __('مقارنة الأدوار') }}</h1>
            <p class="text-sm text-gray-500 mt-1">{{ __('اختر حتى 4 أدوار لمقارنة صلاحياتها جنبًا إلى جنب') }}</p>
        </div>
        <div class="flex items-center gap-2">
            <a href="{{ route('roles.matrix') }}" wire:navigate
               class="inline-flex items-center gap-2 px-3 py-2 text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 text-sm font-medium">
                <svg 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="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/></svg>
                {{ __('المصفوفة') }}
            </a>
            <a href="{{ route('roles.list') }}" wire:navigate
               class="inline-flex items-center gap-2 px-3 py-2 text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 text-sm font-medium">
                &larr; {{ __('قائمة الأدوار') }}
            </a>
        </div>
    </div>

    {{-- Flash Messages --}}
    @if(session('error'))
    <div class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">{{ session('error') }}</div>
    @endif

    {{-- Role Selector --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-4">
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {{-- Add Role --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">{{ __('إضافة دور للمقارنة') }}</label>
                <select wire:change="addRole($event.target.value); $event.target.value = ''"
                        class="w-full text-sm px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="">{{ __('اختر دور...') }}</option>
                    @foreach($allRoles as $role)
                        @if(!in_array($role->id, $selectedRoleIds))
                        <option value="{{ $role->id }}">{{ $role->name_ar }} ({{ $role->level }})</option>
                        @endif
                    @endforeach
                </select>
            </div>

            {{-- Module filter --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">{{ __('تصفية بالوحدة') }}</label>
                <select wire:model.live="filterModule" class="w-full text-sm px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="">{{ __('كل الوحدات') }}</option>
                    @foreach($modules as $mod)
                    <option value="{{ $mod }}">{{ $moduleLabels[$mod] ?? $mod }}</option>
                    @endforeach
                </select>
            </div>

            {{-- Differences toggle --}}
            <div class="flex items-end">
                <button wire:click="toggleDifferencesOnly"
                        class="w-full px-4 py-2 rounded-lg text-sm font-medium transition-colors {{ $showDifferencesOnly ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' }}">
                    {{ $showDifferencesOnly ? __('عرض الاختلافات فقط ✓') : __('عرض الاختلافات فقط') }}
                </button>
            </div>
        </div>

        {{-- Selected Roles Tags --}}
        @if(count($selectedRoleIds) > 0)
        <div class="flex flex-wrap gap-2 mt-3 pt-3 border-t border-gray-100">
            @foreach($selectedRoles as $role)
            <span class="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-blue-50 text-blue-700 text-sm font-medium">
                {{ $role->name_ar }}
                <button wire:click="removeRole({{ $role->id }})" class="ms-1 text-blue-400 hover:text-red-500">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                </button>
            </span>
            @endforeach
        </div>
        @endif
    </div>

    {{-- Comparison Table --}}
    @if($selectedRoles->count() >= 2)
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="sticky start-0 z-10 bg-gray-50 px-4 py-3 text-start text-xs font-semibold text-gray-600 min-w-[220px]">
                            {{ __('الصلاحية') }}
                        </th>
                        @foreach($selectedRoles as $role)
                        <th class="px-3 py-3 text-center text-xs font-semibold text-gray-600 min-w-[100px] whitespace-nowrap">
                            <div>{{ $role->name_ar }}</div>
                            <div class="font-normal text-[10px] text-gray-400">{{ __('مستوى') }} {{ $role->level }}</div>
                        </th>
                        @endforeach
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @foreach($grouped as $module => $permissions)
                    <tr class="bg-gray-50/50">
                        <td colspan="{{ $selectedRoles->count() + 1 }}" class="px-4 py-2">
                            <span class="text-xs font-bold text-gray-800">{{ $moduleLabels[$module] ?? $module }}</span>
                            <span class="text-[10px] text-gray-400 ms-2 font-mono">({{ $module }})</span>
                        </td>
                    </tr>
                    @foreach($permissions as $permission)
                    @php
                        $scopes = $selectedRoles->map(fn ($r) => $pivotData[$r->id][$permission->id] ?? '')->toArray();
                        $hasDifference = count(array_unique($scopes)) > 1;
                    @endphp
                    <tr class="{{ $hasDifference ? 'bg-amber-50/50' : '' }} hover:bg-blue-50/30 transition-colors">
                        <td class="sticky start-0 z-10 bg-white px-4 py-2 border-e border-gray-100 {{ $hasDifference ? '!bg-amber-50/50' : '' }}">
                            <div class="flex flex-col">
                                <span class="text-sm text-gray-800">{{ $this->getActionLabel($permission->action) }}</span>
                                <span class="text-[10px] text-gray-400 font-mono" dir="ltr">{{ $permission->name }}</span>
                            </div>
                        </td>
                        @foreach($selectedRoles as $idx => $role)
                        @php
                            $scope = $pivotData[$role->id][$permission->id] ?? '';
                            $scopeConfig = match($scope) {
                                'own' => ['bg' => 'bg-yellow-100', 'text' => 'text-yellow-800', 'dot' => 'bg-yellow-500', 'label' => 'الخاصة'],
                                'own_groups' => ['bg' => 'bg-orange-100', 'text' => 'text-orange-800', 'dot' => 'bg-orange-500', 'label' => 'مجموعاته'],
                                'own_children' => ['bg' => 'bg-purple-100', 'text' => 'text-purple-800', 'dot' => 'bg-purple-500', 'label' => 'أبنائه'],
                                'branch' => ['bg' => 'bg-blue-100', 'text' => 'text-blue-800', 'dot' => 'bg-blue-500', 'label' => 'الفرع'],
                                'academy' => ['bg' => 'bg-green-100', 'text' => 'text-green-800', 'dot' => 'bg-green-500', 'label' => 'الأكاديمية'],
                                'all' => ['bg' => 'bg-red-100', 'text' => 'text-red-800', 'dot' => 'bg-red-500', 'label' => 'الكل'],
                                default => ['bg' => 'bg-gray-50', 'text' => 'text-gray-400', 'dot' => 'bg-gray-300', 'label' => '—'],
                            };
                            $isDifferent = $hasDifference && $scope !== ($scopes[0] ?? '');
                        @endphp
                        <td class="px-1 py-1.5 text-center">
                            <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium {{ $scopeConfig['bg'] }} {{ $scopeConfig['text'] }} {{ $isDifferent ? 'ring-2 ring-amber-400' : '' }}">
                                <span class="w-1.5 h-1.5 rounded-full {{ $scopeConfig['dot'] }}"></span>
                                {{ $scopeConfig['label'] }}
                            </span>
                        </td>
                        @endforeach
                    </tr>
                    @endforeach
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>

    {{-- Summary Stats --}}
    <div class="mt-4 grid grid-cols-2 sm:grid-cols-4 gap-3">
        @foreach($selectedRoles as $role)
        @php
            $count = count($pivotData[$role->id] ?? []);
            $total = \App\Domain\Identity\Models\Permission::count();
            $pct = $total > 0 ? round($count / $total * 100) : 0;
        @endphp
        <div class="bg-white rounded-lg border border-gray-200 p-3">
            <p class="text-xs text-gray-500">{{ $role->name_ar }}</p>
            <p class="text-lg font-bold text-gray-800">{{ $count }} <span class="text-xs font-normal text-gray-400">/ {{ $total }}</span></p>
            <div class="mt-1 h-1.5 bg-gray-100 rounded-full overflow-hidden">
                <div class="h-full bg-blue-500 rounded-full" style="width: {{ $pct }}%"></div>
            </div>
            <p class="text-[10px] text-gray-400 mt-1">{{ $pct }}%</p>
        </div>
        @endforeach
    </div>
    @elseif(count($selectedRoleIds) === 1)
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-8 text-center">
        <p class="text-gray-500">{{ __('اختر دورًا آخر على الأقل لبدء المقارنة') }}</p>
    </div>
    @else
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-8 text-center">
        <svg class="mx-auto w-12 h-12 text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>
        <p class="text-gray-500 font-medium">{{ __('اختر دورين على الأقل لبدء المقارنة') }}</p>
        <p class="text-gray-400 text-sm mt-1">{{ __('يمكنك مقارنة حتى 4 أدوار في نفس الوقت') }}</p>
    </div>
    @endif
</div>
