<x-app-layout>

    <x-module-hero title="Roles &amp; Permissions" description="Manage system roles and their assigned permissions" icon="fa-user-tag">
        <x-slot name="tabs">
            @can('view users')
            <a href="{{ route('users.index') }}"
               class="module-hero-tab {{ request()->routeIs('users.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-users text-sm"></i> All Users
            </a>
            @endcan
            @role('Super Manager')
            <a href="{{ route('roles.index') }}"
               class="module-hero-tab {{ request()->routeIs('roles.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-user-tag text-sm"></i> Roles
            </a>
            <a href="{{ route('roles.assign') }}"
               class="module-hero-tab {{ request()->routeIs('roles.assign') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-key text-sm"></i> Assign Permissions
            </a>
            @endrole
            @can('manage themes')
            <a href="{{ route('admin.themes.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.themes.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-palette text-sm"></i> Themes
            </a>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-4 md:p-6" x-data="rolesIndex()">

        @if(session('success'))
        <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-xl flex items-center gap-2">
            <i class="fas fa-check-circle"></i> {{ session('success') }}
        </div>
        @endif

        {{-- ── Stats row ── --}}
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-5 border border-blue-200 flex items-center gap-4">
                <div class="w-12 h-12 rounded-xl bg-blue-600 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-users-cog text-white text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-blue-600 font-semibold">Total Roles</p>
                    <p class="text-3xl font-bold text-blue-800">{{ $roles->count() }}</p>
                </div>
            </div>
            <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-5 border border-green-200 flex items-center gap-4">
                <div class="w-12 h-12 rounded-xl bg-green-600 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-key text-white text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-green-600 font-semibold">Total Permissions</p>
                    <p class="text-3xl font-bold text-green-800">{{ \Spatie\Permission\Models\Permission::count() }}</p>
                </div>
            </div>
            <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-5 border border-purple-200 flex items-center gap-4">
                <div class="w-12 h-12 rounded-xl bg-purple-600 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-users text-white text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-purple-600 font-semibold">Total Users</p>
                    <p class="text-3xl font-bold text-purple-800">{{ \App\Models\User::count() }}</p>
                </div>
            </div>
        </div>


        {{-- ── Roles grid ── --}}
        <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 mb-6">
            @foreach($roles as $role)
            @php
                $themeGradients = [
                    'midnight-dark'  => 'from-slate-800 to-slate-700',
                    'ocean-blue'     => 'from-sky-600 to-sky-500',
                    'arctic-white'   => 'from-gray-200 to-gray-100',
                    'desert-sand'    => 'from-amber-600 to-amber-500',
                    'forest-green'   => 'from-emerald-700 to-emerald-600',
                    'royal-purple'   => 'from-violet-700 to-violet-600',
                    'sunset-orange'  => 'from-orange-600 to-orange-500',
                    'corporate-gray' => 'from-slate-600 to-slate-500',
                    'cherry-blossom' => 'from-pink-600 to-pink-500',
                    'crimson-red'    => 'from-red-700 to-red-600',
                    'default'        => 'from-gray-600 to-gray-500',
                ];
                $grad = $themeGradients[$role->theme ?? 'default'] ?? $themeGradients['default'];
                $isLight = in_array($role->theme ?? 'default', ['arctic-white']);
                $textColor = $isLight ? 'text-gray-800' : 'text-white';
                $permList = $role->permissions->pluck('name')->sort()->values();
            @endphp
            <div class="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden hover:shadow-md transition-shadow">
                {{-- Card header --}}
                <div class="bg-gradient-to-r {{ $grad }} px-5 py-4 flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-lg bg-white/20 flex items-center justify-center">
                            <i class="fas fa-user-tag {{ $textColor }} text-lg"></i>
                        </div>
                        <div>
                            <h3 class="font-bold {{ $textColor }} text-base leading-tight">{{ $role->name }}</h3>
                            <p class="{{ $textColor }} opacity-75 text-xs capitalize">{{ str_replace('-', ' ', $role->theme ?? 'default') }}</p>
                        </div>
                    </div>
                    <div class="text-right">
                        <span class="inline-block px-2.5 py-1 bg-white/20 {{ $textColor }} rounded-full text-xs font-bold">
                            {{ $role->permissions->count() }} perms
                        </span>
                    </div>
                </div>

                {{-- Card body --}}
                <div class="p-4">
                    <div class="flex items-center justify-between mb-3">
                        <div class="flex items-center gap-4 text-sm text-gray-600">
                            <span class="flex items-center gap-1.5">
                                <i class="fas fa-users text-blue-500 text-xs"></i>
                                <span class="font-semibold text-gray-800">{{ $role->users->count() }}</span> users
                            </span>
                            <span class="flex items-center gap-1.5">
                                <i class="fas fa-key text-green-500 text-xs"></i>
                                <span class="font-semibold text-gray-800">{{ $role->permissions->count() }}</span> permissions
                            </span>
                        </div>
                    </div>

                    {{-- Permission preview (first 5) --}}
                    @if($role->permissions->count() > 0)
                    <div class="flex flex-wrap gap-1 mb-3">
                        @foreach($permList->take(5) as $perm)
                        <span class="px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-[10px] font-medium">{{ $perm }}</span>
                        @endforeach
                        @if($permList->count() > 5)
                        <span class="px-2 py-0.5 bg-blue-100 text-blue-600 rounded text-[10px] font-semibold">+{{ $permList->count() - 5 }} more</span>
                        @endif
                    </div>
                    @else
                    <p class="text-xs text-gray-400 italic mb-3">No permissions assigned</p>
                    @endif

                    {{-- Actions --}}
                    <div class="flex items-center gap-2 pt-2 border-t border-gray-100">
                        <a href="{{ route('roles.assign') }}"
                           class="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-semibold transition-colors">
                            <i class="fas fa-key"></i> Manage Permissions
                        </a>
                        <button
                            @click="openModal({{ $role->id }}, '{{ addslashes($role->name) }}', {{ $permList->toJson() }})"
                            class="flex items-center justify-center gap-1.5 px-3 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-xs font-semibold transition-colors">
                            <i class="fas fa-eye"></i> View All
                        </button>
                    </div>
                </div>
            </div>
            @endforeach
        </div>


        {{-- ── Permissions Modal ── --}}
        <div x-show="modal.show"
             x-transition:enter="transition ease-out duration-200"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             x-transition:leave="transition ease-in duration-150"
             x-transition:leave-start="opacity-100"
             x-transition:leave-end="opacity-0"
             class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50"
             @click.self="modal.show = false"
             @keydown.escape.window="modal.show = false"
             style="display:none;">
            <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] flex flex-col"
                 x-transition:enter="transition ease-out duration-200"
                 x-transition:enter-start="opacity-0 scale-95"
                 x-transition:enter-end="opacity-100 scale-100">
                {{-- Modal header --}}
                <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-indigo-600 to-indigo-700 rounded-t-2xl">
                    <div>
                        <h3 class="text-base font-semibold text-white" x-text="modal.roleName + ' — Permissions'"></h3>
                        <p class="text-xs text-indigo-200" x-text="modal.permissions.length + ' permissions assigned'"></p>
                    </div>
                    <button @click="modal.show = false"
                            class="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-white/20 text-white/80 hover:text-white transition">
                        <i class="fas fa-times"></i>
                    </button>
                </div>

                {{-- Search inside modal --}}
                <div class="px-6 py-3 border-b border-gray-100">
                    <div class="relative">
                        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                        <input type="text" x-model="modal.search"
                               placeholder="Filter permissions..."
                               class="w-full pl-9 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                </div>

                {{-- Permission list --}}
                <div class="flex-1 overflow-y-auto px-6 py-4">
                    <template x-if="modal.permissions.length === 0">
                        <p class="text-center text-gray-400 py-8 text-sm">No permissions assigned to this role.</p>
                    </template>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-1.5">
                        <template x-for="perm in filteredModalPerms()" :key="perm">
                            <div class="flex items-center gap-2 px-3 py-2 bg-gray-50 rounded-lg border border-gray-200">
                                <i class="fas fa-check-circle text-green-500 text-xs flex-shrink-0"></i>
                                <span class="text-xs text-gray-700 font-medium" x-text="perm"></span>
                            </div>
                        </template>
                        <template x-if="filteredModalPerms().length === 0 && modal.search">
                            <div class="col-span-2 text-center text-gray-400 py-6 text-sm">
                                No permissions match "<span x-text="modal.search"></span>"
                            </div>
                        </template>
                    </div>
                </div>

                {{-- Modal footer --}}
                <div class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
                    <a :href="'{{ route('roles.assign') }}'"
                       class="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-semibold transition-colors">
                        <i class="fas fa-key"></i> Manage Permissions
                    </a>
                    <button @click="modal.show = false"
                            class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-semibold transition-colors">
                        Close
                    </button>
                </div>
            </div>
        </div>

    </div>{{-- end x-data --}}

    @push('scripts')
    <script>
    function rolesIndex() {
        return {
            modal: { show: false, roleId: null, roleName: '', permissions: [], search: '' },

            openModal(roleId, roleName, permissions) {
                this.modal = { show: true, roleId, roleName, permissions, search: '' };
            },

            filteredModalPerms() {
                if (!this.modal.search) return this.modal.permissions;
                const q = this.modal.search.toLowerCase();
                return this.modal.permissions.filter(p => p.toLowerCase().includes(q));
            },
        };
    }
    </script>
    @endpush

</x-app-layout>
