<div class="py-8 max-w-7xl mx-auto sm:px-6 lg:px-8">

    {{-- Cabecera: nombre del rol + botón Volver --}}
    <x-slot name="header">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
                <x-heroicon-o-shield-check class="w-6 h-6 text-primary" />
                {{ $role->name }}
                @if($isProtected)
                    <span class="badge badge-ghost badge-sm">{{ __('protected') }}</span>
                @endif
            </h2>
            <a href="{{ route('admin.roles') }}" class="btn btn-ghost btn-sm gap-1" wire:navigate>
                <x-heroicon-o-arrow-left class="w-4 h-4" /> {{ __('Back') }}
            </a>
        </div>
    </x-slot>

    {{-- Tabs --}}
    <div class="flex flex-wrap gap-1 mb-4">
        <button wire:click="setTab('ficha')" class="btn btn-sm {{ $tab === 'ficha' ? 'btn-primary' : 'btn-ghost' }}">
            {{ __('Details') }}
        </button>
        <button wire:click="setTab('permisos')" class="btn btn-sm {{ $tab === 'permisos' ? 'btn-primary' : 'btn-ghost' }}">
            {{ __('Permissions') }}
        </button>
    </div>

    {{-- ═══════════════ TAB FICHA ═══════════════ --}}
    @if($tab === 'ficha')
        <div class="bg-white rounded-lg shadow p-6 mb-6">
            <div class="flex items-start justify-between gap-4">
                <div class="flex-1">
                    <h3 class="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-1">{{ __('Description') }}</h3>
                    <p class="text-gray-700">{{ $role->description ?: __('No description') }}</p>
                </div>
                <div class="flex items-center gap-2 shrink-0">
                    <a href="{{ route('admin.roles.edit', $role->id) }}" class="btn btn-sm btn-info gap-1" wire:navigate>
                        <x-heroicon-o-pencil class="w-4 h-4" /> {{ __('Edit') }}
                    </a>
                    @unless($isProtected)
                        <button wire:click="delete"
                                wire:confirm="{{ __('Delete role') }} '{{ $role->name }}'?"
                                class="btn btn-sm btn-error btn-outline gap-1">
                            <x-heroicon-o-trash class="w-4 h-4" /> {{ __('Delete') }}
                        </button>
                    @endunless
                </div>
            </div>
        </div>

        {{-- Usuarios con este rol --}}
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="px-6 py-3 border-b border-base-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                <h3 class="font-semibold text-gray-700">{{ __('Users with this role') }} ({{ $users->count() }})</h3>
                {{-- Formulario para añadir un usuario al rol --}}
                <form wire:submit.prevent="addUser" class="flex items-center gap-2">
                    <select wire:model="newUserId" class="select select-bordered select-sm w-56 @error('newUserId') select-error @enderror">
                        <option value="">{{ __('Select a user...') }}</option>
                        @foreach($availableUsers as $au)
                            <option value="{{ $au->id }}">
                                {{ trim(($au->first_name ?? '').' '.($au->last_name ?? '')) ?: $au->name }} — {{ $au->email }}
                            </option>
                        @endforeach
                    </select>
                    <button class="btn btn-sm btn-primary gap-1">
                        <x-heroicon-o-plus class="w-4 h-4" /> {{ __('Add') }}
                    </button>
                </form>
            </div>
            @error('newUserId') <p class="text-error text-xs px-6 pt-2">{{ $message }}</p> @enderror
            <div class="overflow-x-auto">
                <table class="table table-zebra">
                    <thead>
                        <tr>
                            <th>{{ __('Name') }}</th>
                            <th>{{ __('Last name') }}</th>
                            <th>{{ __('Status') }}</th>
                            <th class="w-12"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($users as $u)
                            <tr wire:key="ru-{{ $u->id }}" class="hover">
                                <td>
                                    <div class="flex items-center gap-3">
                                        <div class="avatar placeholder">
                                            <div class="bg-neutral text-neutral-content rounded-full w-8">
                                                <span class="text-xs">{{ strtoupper(mb_substr($u->first_name ?: $u->name, 0, 1)) }}</span>
                                            </div>
                                        </div>
                                        <div>
                                            <p class="font-medium text-sm leading-tight">{{ $u->first_name ?: $u->name }}</p>
                                            <p class="text-xs text-gray-500">{{ $u->email }}</p>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-sm">{{ $u->last_name ?: '—' }}</td>
                                <td>
                                    @php
                                        [$cls, $label] = match($u->status) {
                                            'active'    => ['badge-success', __('Active')],
                                            'inactive'  => ['badge-ghost',   __('Inactive')],
                                            'suspended' => ['badge-error',    __('Suspended')],
                                            default     => ['badge-ghost', ucfirst((string) $u->status)],
                                        };
                                    @endphp
                                    <span class="badge badge-sm {{ $cls }}">{{ $label }}</span>
                                </td>
                                <td class="text-right">
                                    <button wire:click="removeUser({{ $u->id }})"
                                            wire:confirm="{{ __('Remove this user from the role?') }}"
                                            class="btn btn-ghost btn-xs text-error" title="{{ __('Remove') }}">
                                        <x-heroicon-o-x-mark class="w-4 h-4" />
                                    </button>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="4" class="text-center text-gray-400 py-8">{{ __('No users with this role') }}</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    @endif

    {{-- ═══════════════ TAB PERMISOS ═══════════════ --}}
    @if($tab === 'permisos')
        <div class="space-y-3">
            @forelse($grouped as $section => $perms)
                <div x-data="{ open: true }" class="bg-white rounded-lg shadow overflow-hidden">
                    {{-- Cabecera del grupo: colapsable + marcar/desmarcar todo --}}
                    <div class="flex items-center justify-between px-4 py-3 bg-base-200/60">
                        <button type="button" @click="open = !open" class="flex items-center gap-2 flex-1 text-left">
                            <span class="transition-transform duration-200" :class="open ? 'rotate-90' : ''">
                                <x-heroicon-o-chevron-right class="w-4 h-4 text-gray-500" />
                            </span>
                            <span class="font-semibold text-gray-700">{{ $section }}</span>
                            <span class="badge badge-ghost badge-sm">{{ $perms->count() }}</span>
                        </button>
                        <div class="flex items-center gap-1 shrink-0">
                            <button wire:click="setGroup('{{ $section }}', true)" class="btn btn-xs btn-ghost gap-1" title="{{ __('Check all') }}">
                                <x-heroicon-o-check class="w-3.5 h-3.5" /> {{ __('All') }}
                            </button>
                            <button wire:click="setGroup('{{ $section }}', false)" class="btn btn-xs btn-ghost gap-1" title="{{ __('Uncheck all') }}">
                                <x-heroicon-o-x-mark class="w-3.5 h-3.5" /> {{ __('None') }}
                            </button>
                        </div>
                    </div>

                    {{-- Lista de permisos: una sola columna (permiso izquierda, switch derecha) --}}
                    <div x-show="open" x-transition.opacity class="divide-y divide-base-200">
                        @foreach($perms as $perm)
                            <label class="flex items-center justify-between gap-3 px-4 py-2.5 cursor-pointer hover:bg-base-100">
                                <div class="min-w-0">
                                    <span class="text-sm font-medium">{{ $perm->name }}</span>
                                    @if($perm->description)
                                        <p class="text-xs text-gray-400 leading-tight">{{ $perm->description }}</p>
                                    @endif
                                </div>
                                <input type="checkbox"
                                       class="toggle toggle-sm toggle-primary"
                                       wire:key="perm-{{ $role->id }}-{{ $perm->id }}"
                                       @checked(in_array($perm->name, $rolePerms, true))
                                       wire:click="togglePermission('{{ $perm->name }}')" />
                            </label>
                        @endforeach
                    </div>
                </div>
            @empty
                <p class="text-gray-400 text-sm">{{ __('No permissions') }}</p>
            @endforelse
        </div>
    @endif
</div>
