<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">{{ __('عرض وإدارة صلاحيات كل دور في النظام') }}</p>
        </div>
        <div class="flex items-center gap-2">
            <a href="{{ route('roles.compare') }}" 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="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>
                <span class="hidden sm:inline">{{ __('مقارنة') }}</span>
            </a>
            @can('roles.create')
            <a href="{{ route('roles.create') }}" wire:navigate
               class="inline-flex items-center gap-2 px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 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="M12 4v16m8-8H4"/></svg>
                <span class="hidden sm:inline">{{ __('دور جديد') }}</span>
            </a>
            @endcan
            <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

    {{-- Legend --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-4">
        <div class="flex flex-wrap items-center gap-4">
            <span class="text-sm font-semibold text-gray-700">{{ __('مفتاح النطاقات:') }}</span>
            <div class="flex flex-wrap gap-2">
                <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-gray-100 text-gray-600">
                    <span class="w-2 h-2 rounded-full bg-gray-400"></span>
                    {{ __('لا يوجد') }}
                </span>
                <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-yellow-100 text-yellow-800">
                    <span class="w-2 h-2 rounded-full bg-yellow-500"></span>
                    {{ __('الخاصة') }}
                </span>
                <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-orange-100 text-orange-800">
                    <span class="w-2 h-2 rounded-full bg-orange-500"></span>
                    {{ __('مجموعاته') }}
                </span>
                <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-purple-100 text-purple-800">
                    <span class="w-2 h-2 rounded-full bg-purple-500"></span>
                    {{ __('أبنائه') }}
                </span>
                <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
                    <span class="w-2 h-2 rounded-full bg-blue-500"></span>
                    {{ __('الفرع') }}
                </span>
                <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800">
                    <span class="w-2 h-2 rounded-full bg-green-500"></span>
                    {{ __('الأكاديمية') }}
                </span>
                <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-800">
                    <span class="w-2 h-2 rounded-full bg-red-500"></span>
                    {{ __('الكل') }}
                </span>
            </div>
        </div>
        <p class="text-xs text-gray-500 mt-2">{{ __('اضغط على أي خلية لتدوير النطاق (لا يوجد ← الخاصة ← مجموعاته ← الفرع ← الأكاديمية ← الكل ← لا يوجد). يمكنك تعديل صلاحيات الأدوار الأقل مستوى منك فقط.') }}</p>
    </div>

    {{-- Filters --}}
    <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-2 gap-4">
            <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>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">{{ __('تصفية بالدور') }}</label>
                <select wire:model.live="filterRole" 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($roles as $role)
                    <option value="{{ $role->slug }}">{{ $role->name_ar }}</option>
                    @endforeach
                </select>
            </div>
        </div>
    </div>

    {{-- Matrix Table --}}
    <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($roles as $role)
                        <th class="px-3 py-3 text-center text-xs font-semibold text-gray-600 min-w-[90px] whitespace-nowrap">
                            <div class="flex items-center justify-center gap-1">
                                <span>{{ $role->name_ar }}</span>
                                @if($canEditRole[$role->id] ?? false)
                                <a href="{{ route('roles.edit', $role) }}" wire:navigate class="text-gray-400 hover:text-blue-600" title="{{ __('تعديل الدور') }}">
                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                                </a>
                                @endif
                            </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)
                    {{-- Module header row --}}
                    <tr class="bg-gray-50/50">
                        <td colspan="{{ $roles->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)
                    <tr class="hover:bg-blue-50/30 transition-colors">
                        {{-- Permission name cell --}}
                        <td class="sticky start-0 z-10 bg-white px-4 py-2 border-e border-gray-100">
                            <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>
                                @if($permission->description_ar)
                                <span class="text-[10px] text-gray-500">{{ $permission->description_ar }}</span>
                                @endif
                            </div>
                        </td>
                        {{-- Role cells --}}
                        @foreach($roles as $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' => '—'],
                            };
                        @endphp
                        <td class="px-1 py-1.5 text-center">
                            @if(!($canEditRole[$role->id] ?? false))
                            <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium {{ $scopeConfig['bg'] }} {{ $scopeConfig['text'] }}"
                                  title="{{ $scope ? ($scopeLabels[$scope] ?? $scope) : __('لا يوجد') }}">
                                <span class="w-1.5 h-1.5 rounded-full {{ $scopeConfig['dot'] }}"></span>
                                {{ $scopeConfig['label'] }}
                            </span>
                            @else
                            <button wire:click="togglePermission({{ $role->id }}, {{ $permission->id }}, '{{ $scope }}')"
                                    class="inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium {{ $scopeConfig['bg'] }} {{ $scopeConfig['text'] }} hover:ring-2 hover:ring-blue-300 transition-all cursor-pointer"
                                    title="{{ __('اضغط لتغيير النطاق') }}">
                                <span class="w-1.5 h-1.5 rounded-full {{ $scopeConfig['dot'] }}"></span>
                                {{ $scopeConfig['label'] }}
                            </button>
                            @endif
                        </td>
                        @endforeach
                    </tr>
                    @endforeach
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>

    {{-- Stats --}}
    <div class="mt-4 grid grid-cols-2 sm:grid-cols-4 gap-3">
        @foreach($roles->take(8) as $role)
        @php
            $count = count($pivotData[$role->id] ?? []);
            $total = $grouped->flatten()->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>
        </div>
        @endforeach
    </div>
</div>
