<x-admin-layout title="Usuários">
<div x-data="usuariosApp()" x-init="init()">

    {{-- Header --}}
    <div style="display:flex; align-items:flex-start; justify-content:space-between; gap:1rem; margin-bottom:1.5rem; flex-wrap:wrap;">
        <div>
            <h1 style="font-size:1.25rem; font-weight:700; color:#1e3a5f; margin:0 0 3px;">Usuários do sistema</h1>
            <p style="font-size:0.8125rem; color:#94a3b8; margin:0;">Gerencie acessos e permissões por módulo</p>
        </div>
        <button @click="openCreate()"
                style="display:inline-flex; align-items:center; gap:0.5rem; padding:0.5rem 1.125rem; background:#25b87e; color:#fff; font-size:0.875rem; font-weight:600; border:none; border-radius:10px; cursor:pointer; white-space:nowrap; flex-shrink:0;">
            <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
            </svg>
            Novo usuário
        </button>
    </div>

    {{-- Table --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:16px; overflow:hidden;">
        <div style="overflow-x:auto;">
            <table style="width:100%; border-collapse:collapse; min-width:640px;">
                <thead>
                    <tr style="border-bottom:1px solid #f1f5f9; background:#fafbfc;">
                        <th style="padding:0.75rem 1.25rem; text-align:left; font-size:0.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.06em; white-space:nowrap;">Usuário</th>
                        <th style="padding:0.75rem 1rem; text-align:left; font-size:0.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.06em; white-space:nowrap;">E-mail</th>
                        <th style="padding:0.75rem 1rem; text-align:left; font-size:0.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.06em; white-space:nowrap;">Função</th>
                        <th style="padding:0.75rem 1rem; text-align:left; font-size:0.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.06em; white-space:nowrap;">Módulos</th>
                        <th style="padding:0.75rem 1rem; width:90px;"></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($users as $user)
                    @php
                        $role      = $user->roles->first()?->name ?? 'sem papel';
                        $isAdmin   = $role === 'admin';
                        $userPerms = $isAdmin
                            ? $allPerms
                            : $user->getDirectPermissions()->pluck('name')->toArray();
                        $permLabels = [
                            'acessar_kanban'      => ['label' => 'Kanban',     'bg' => '#dbeafe', 'color' => '#1d4ed8'],
                            'acessar_leads'       => ['label' => 'Leads',      'bg' => '#ede9fe', 'color' => '#7c3aed'],
                            'acessar_contratos'   => ['label' => 'Contratos',  'bg' => '#fef3c7', 'color' => '#92400e'],
                            'acessar_financeiro'  => ['label' => 'Financeiro', 'bg' => '#dcfce7', 'color' => '#15803d'],
                            'acessar_obrigacoes'  => ['label' => 'Obrigações', 'bg' => '#fce7f3', 'color' => '#9d174d'],
                            'acessar_documentos'  => ['label' => 'Documentos', 'bg' => '#e0f2fe', 'color' => '#0369a1'],
                        ];
                        $roleColors = [
                            'admin'        => ['bg' => '#fee2e2', 'color' => '#dc2626'],
                            'contador'     => ['bg' => '#dbeafe', 'color' => '#2563eb'],
                            'visualizador' => ['bg' => '#f1f5f9', 'color' => '#64748b'],
                        ];
                        $rc = $roleColors[$role] ?? $roleColors['visualizador'];
                    @endphp
                    <tr style="border-bottom:1px solid #f8fafc; transition:background 0.1s;"
                        onmouseover="this.style.background='#fafbfc'" onmouseout="this.style.background='transparent'">

                        <td style="padding:0.875rem 1.25rem;">
                            <div style="display:flex; align-items:center; gap:0.75rem;">
                                <div style="width:36px; height:36px; border-radius:10px; background:#e8f8f1; display:flex; align-items:center; justify-content:center; font-size:0.8125rem; font-weight:700; color:#25b87e; flex-shrink:0; letter-spacing:0.02em;">
                                    {{ strtoupper(substr($user->name, 0, 2)) }}
                                </div>
                                <div>
                                    <p style="font-size:0.875rem; font-weight:600; color:#1e3a5f; margin:0 0 1px; white-space:nowrap;">{{ $user->name }}</p>
                                    @if($user->id === auth()->id())
                                        <span style="font-size:0.6875rem; color:#25b87e; font-weight:600;">Você</span>
                                    @else
                                        <span style="font-size:0.6875rem; color:#94a3b8;">{{ $user->created_at->format('d/m/Y') }}</span>
                                    @endif
                                </div>
                            </div>
                        </td>

                        <td style="padding:0.875rem 1rem; font-size:0.8125rem; color:#64748b; white-space:nowrap;">{{ $user->email }}</td>

                        <td style="padding:0.875rem 1rem;">
                            <span style="padding:0.25rem 0.625rem; border-radius:100px; font-size:0.75rem; font-weight:600; background:{{ $rc['bg'] }}; color:{{ $rc['color'] }}; white-space:nowrap;">
                                {{ ucfirst($role) }}
                            </span>
                        </td>

                        <td style="padding:0.875rem 1rem;">
                            @if($isAdmin)
                                <span style="padding:0.2rem 0.5rem; border-radius:100px; font-size:0.6875rem; font-weight:700; background:#f0fdf4; color:#16a34a; border:1px solid #bbf7d0; white-space:nowrap;">
                                    Acesso total
                                </span>
                            @else
                                <div style="display:flex; gap:0.25rem; flex-wrap:wrap;">
                                    @forelse(array_intersect($userPerms, $allPerms) as $perm)
                                        @if(isset($permLabels[$perm]))
                                            <span style="padding:0.2rem 0.5rem; border-radius:100px; font-size:0.6875rem; font-weight:600; background:{{ $permLabels[$perm]['bg'] }}; color:{{ $permLabels[$perm]['color'] }}; white-space:nowrap;">
                                                {{ $permLabels[$perm]['label'] }}
                                            </span>
                                        @endif
                                    @empty
                                        <span style="font-size:0.75rem; color:#cbd5e1;">Nenhum</span>
                                    @endforelse
                                </div>
                            @endif
                        </td>

                        <td style="padding:0.875rem 1rem; text-align:right;">
                            <div style="display:flex; gap:0.375rem; justify-content:flex-end;">
                                <button @click="openEdit({{ $user->id }}, {{ json_encode($user->name) }}, {{ json_encode($user->email) }}, {{ json_encode($role) }}, {{ json_encode($userPerms) }})"
                                        style="padding:0.3125rem 0.625rem; border:1px solid #e2e8f0; border-radius:7px; background:#fff; color:#1e3a5f; font-size:0.75rem; font-weight:500; cursor:pointer; white-space:nowrap; transition:all 0.15s;"
                                        onmouseover="this.style.borderColor='#cbd5e1'; this.style.background='#f8fafc';"
                                        onmouseout="this.style.borderColor='#e2e8f0'; this.style.background='#fff';">
                                    Editar
                                </button>
                                @if($user->id !== auth()->id())
                                <button @click="deleteUser({{ $user->id }}, {{ json_encode($user->name) }})"
                                        style="padding:0.3125rem 0.625rem; border:1px solid #fecaca; border-radius:7px; background:#fff; color:#ef4444; font-size:0.75rem; font-weight:500; cursor:pointer; white-space:nowrap; transition:all 0.15s;"
                                        onmouseover="this.style.background='#fef2f2';"
                                        onmouseout="this.style.background='#fff';">
                                    Excluir
                                </button>
                                @endif
                            </div>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>

    {{-- Modal --}}
    <div x-show="modal"
         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"
         @keydown.escape.window="modal=false"
         style="position:fixed; inset:0; z-index:200; background:rgba(15,23,42,0.5); backdrop-filter:blur(3px);">

        {{-- Centering layer --}}
        <div style="display:flex; align-items:center; justify-content:center; min-height:100%; width:100%; padding:1rem;">

        {{-- Panel --}}
        <div @click.stop
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
             style="background:#fff; border-radius:20px; width:100%; max-width:520px; max-height:90vh; overflow-y:auto; box-shadow:0 32px 80px rgba(0,0,0,0.22);">

            {{-- Header --}}
            <div style="background:linear-gradient(135deg,#1e3a5f 0%,#162e4a 100%); border-radius:20px 20px 0 0; display:flex; align-items:center; justify-content:space-between; padding:1.25rem 1.375rem; position:sticky; top:0; z-index:1;">
                <div>
                    <h3 x-text="editId ? 'Editar usuário' : 'Novo usuário'" style="font-size:1.0625rem; font-weight:700; color:#fff; margin:0 0 2px;"></h3>
                    <p style="font-size:0.75rem; color:rgba(255,255,255,0.45); margin:0;">Preencha os dados e defina o nível de acesso</p>
                </div>
                <button @click="modal=false"
                        style="width:30px; height:30px; border-radius:8px; border:1px solid rgba(255,255,255,0.15); background:rgba(255,255,255,0.08); color:rgba(255,255,255,0.6); cursor:pointer; display:flex; align-items:center; justify-content:center; flex-shrink:0; transition:all 0.15s;"
                        onmouseover="this.style.background='rgba(255,255,255,0.15)'" onmouseout="this.style.background='rgba(255,255,255,0.08)'">
                    <svg width="13" height="13" 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>
            </div>

            {{-- Body --}}
            <div style="background:#f8fafc; padding:1.375rem 1.5rem; display:flex; flex-direction:column; gap:1.375rem;">

                {{-- Section: Dados do usuário --}}
                <div style="background:#fff; border:1px solid #eef2f7; border-radius:14px; padding:1.125rem 1.25rem; display:flex; flex-direction:column; gap:1rem;">
                    <p style="font-size:0.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.07em; margin:0;">Dados do usuário</p>

                    <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.875rem;">
                        <div>
                            <label class="ulabel">Nome completo</label>
                            <input x-model="form.name" type="text" placeholder="João Silva" class="uinput">
                        </div>
                        <div>
                            <label class="ulabel">E-mail</label>
                            <input x-model="form.email" type="email" placeholder="joao@empresa.com" class="uinput">
                        </div>
                    </div>

                    <div>
                        <label class="ulabel">
                            Senha
                            <span x-show="editId" style="font-weight:400; color:#94a3b8; margin-left:0.25rem;">(deixe em branco para não alterar)</span>
                        </label>
                        <input x-model="form.password" type="password" placeholder="Mínimo 8 caracteres" class="uinput">
                    </div>
                </div>

                {{-- Section: Função --}}
                <div style="background:#fff; border:1px solid #eef2f7; border-radius:14px; padding:1.125rem 1.25rem;">
                    <p style="font-size:0.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.07em; margin:0 0 0.75rem;">Função no sistema</p>
                    <div style="display:grid; grid-template-columns:repeat(3, 1fr); gap:0.5rem;">
                        <template x-for="r in roles" :key="r.name">
                            <label style="cursor:pointer;">
                                <input type="radio" :value="r.name" x-model="form.role" class="sr-only">
                                <div style="padding:0.625rem 0.5rem; border-radius:10px; border:2px solid; text-align:center; transition:all 0.15s; cursor:pointer;"
                                     :style="form.role === r.name
                                         ? 'border-color:' + r.color + '; background:' + r.bg + ';'
                                         : 'border-color:#e2e8f0; background:#f8fafc;'"
                                     @click="form.role = r.name">
                                    <p style="font-size:0.8125rem; font-weight:700; margin:0 0 1px;"
                                       :style="'color:' + (form.role === r.name ? r.color : '#1e3a5f');"
                                       x-text="r.label"></p>
                                    <p style="font-size:0.6875rem; margin:0;"
                                       :style="'color:' + (form.role === r.name ? r.color : '#94a3b8');"
                                       x-text="r.desc"></p>
                                </div>
                            </label>
                        </template>
                    </div>
                </div>

                {{-- Section: Permissões (não-admin) --}}
                <div x-show="form.role !== 'admin'"
                     x-transition:enter="transition ease-out duration-150"
                     x-transition:enter-start="opacity-0"
                     x-transition:enter-end="opacity-100"
                     style="background:#fff; border:1px solid #eef2f7; border-radius:14px; padding:1.125rem 1.25rem; display:flex; flex-direction:column; gap:0.75rem;">

                    <p style="font-size:0.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.07em; margin:0;">Acesso aos módulos</p>

                    <template x-for="group in groups" :key="group.key">
                        <div style="border:1.5px solid #e2e8f0; border-radius:10px; overflow:hidden;">

                            {{-- Group header --}}
                            <label style="display:flex; align-items:center; gap:0.625rem; padding:0.6875rem 0.875rem; background:#f8fafc; cursor:pointer; user-select:none; border-bottom:1px solid #e2e8f0;">
                                <input type="checkbox"
                                       :id="'grp_' + group.key"
                                       :checked="isGroupAll(group)"
                                       x-effect="$el.indeterminate = isGroupPartial(group)"
                                       @change="toggleGroup(group, $event.target.checked)"
                                       style="width:15px; height:15px; accent-color:#25b87e; cursor:pointer; flex-shrink:0;">
                                <span style="font-size:0.8125rem; font-weight:700; color:#1e3a5f; flex:1;" x-text="group.label"></span>
                                <span style="font-size:0.6875rem; color:#94a3b8;" x-text="checkedInGroup(group) + '/' + group.perms.length"></span>
                            </label>

                            {{-- Permissions --}}
                            <template x-for="(perm, idx) in group.perms" :key="perm.key">
                                <label :style="idx < group.perms.length - 1 ? 'border-bottom:1px solid #f1f5f9;' : ''"
                                       style="display:flex; align-items:center; gap:0.75rem; padding:0.625rem 0.875rem 0.625rem 2.25rem; cursor:pointer; transition:background 0.1s;"
                                       onmouseover="this.style.background='#fafbfc'" onmouseout="this.style.background='transparent'">
                                    <input type="checkbox"
                                           :checked="hasPerm(perm.key)"
                                           @change="togglePerm(perm.key)"
                                           style="width:15px; height:15px; accent-color:#25b87e; cursor:pointer; flex-shrink:0;">
                                    <div>
                                        <p style="font-size:0.8125rem; font-weight:600; color:#334155; margin:0 0 1px;" x-text="perm.label"></p>
                                        <p style="font-size:0.6875rem; color:#94a3b8; margin:0;" x-text="perm.desc"></p>
                                    </div>
                                </label>
                            </template>

                        </div>
                    </template>
                </div>

                {{-- Section: Admin notice --}}
                <div x-show="form.role === 'admin'"
                     x-transition:enter="transition ease-out duration-150"
                     x-transition:enter-start="opacity-0"
                     x-transition:enter-end="opacity-100"
                     style="padding:0.875rem; background:#f0fdf4; border:1.5px solid #bbf7d0; border-radius:12px; display:flex; align-items:center; gap:0.75rem;">
                    <div style="width:32px; height:32px; border-radius:8px; background:#dcfce7; display:flex; align-items:center; justify-content:center; flex-shrink:0;">
                        <svg width="16" height="16" fill="none" stroke="#16a34a" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
                        </svg>
                    </div>
                    <div>
                        <p style="font-size:0.8125rem; font-weight:700; color:#15803d; margin:0 0 1px;">Administrador — Acesso total</p>
                        <p style="font-size:0.75rem; color:#16a34a; margin:0;">Acessa todos os módulos automaticamente</p>
                    </div>
                </div>

                {{-- Erro --}}
                <div x-show="error"
                     style="padding:0.75rem 0.875rem; background:#fef2f2; border:1px solid #fecaca; border-radius:10px; font-size:0.8125rem; color:#dc2626;"
                     x-text="error"></div>

            </div>

            {{-- Footer --}}
            <div style="padding:1rem 1.5rem; border-top:1.5px solid #eef2f7; display:flex; gap:0.625rem; background:#fff; border-radius:0 0 20px 20px;">
                <button @click="modal=false"
                        style="flex:1; padding:0.625rem 1rem; border:1.5px solid #e2e8f0; border-radius:10px; background:#fff; color:#64748b; font-size:0.875rem; font-weight:500; cursor:pointer; transition:all 0.15s;"
                        onmouseover="this.style.background='#f8fafc';" onmouseout="this.style.background='#fff';">
                    Cancelar
                </button>
                <button @click="save()" :disabled="saving"
                        style="flex:2; padding:0.625rem 1rem; background:#25b87e; border:none; border-radius:10px; color:#fff; font-size:0.875rem; font-weight:600; cursor:pointer; transition:all 0.15s;"
                        :style="saving ? 'opacity:0.65; cursor:not-allowed;' : ''"
                        onmouseover="if(!this.disabled) this.style.background='#1fa06d';"
                        onmouseout="this.style.background='#25b87e';">
                    <span x-text="saving ? 'Salvando...' : (editId ? 'Salvar alterações' : 'Criar usuário')"></span>
                </button>
            </div>

        </div>
        </div>
    </div>

</div>

<style>
.ulabel { display:block; font-size:0.75rem; font-weight:600; color:#475569; margin-bottom:0.3rem; letter-spacing:0.01em; }
.uinput { width:100%; border:1.5px solid #e2e8f0; border-radius:10px; padding:0.65rem 0.85rem; font-size:0.875rem; color:#1e3a5f; background:#fff; outline:none; transition:border-color 0.15s, box-shadow 0.15s; box-sizing:border-box; font-family:inherit; }
.uinput:focus { border-color:#25b87e; box-shadow:0 0 0 3px rgba(37,184,126,0.12); }
.uinput::placeholder { color:#cbd5e1; }
</style>

<script>
function usuariosApp() {
    return {
        modal: false,
        editId: null,
        saving: false,
        error: '',

        form: { name: '', email: '', password: '', role: 'contador', permissions: [] },

        roles: [
            { name: 'admin',        label: 'Admin',        desc: 'Acesso total',     color: '#dc2626', bg: '#fef2f2' },
            { name: 'contador',     label: 'Contador',     desc: 'Ops. internas',    color: '#2563eb', bg: '#eff6ff' },
            { name: 'visualizador', label: 'Visualizador', desc: 'Somente leitura',  color: '#64748b', bg: '#f8fafc' },
        ],

        groups: [
            {
                key: 'operacional',
                label: 'Operacional',
                perms: [
                    { key: 'acessar_kanban',    label: 'Kanban',    desc: 'Gestão de tarefas e demandas' },
                    { key: 'acessar_leads',     label: 'Leads',     desc: 'CRM e gestão de oportunidades' },
                    { key: 'acessar_contratos', label: 'Contratos', desc: 'Documentos e modelos' },
                ],
            },
            {
                key: 'contabil',
                label: 'Gestão Contábil',
                perms: [
                    { key: 'acessar_financeiro',  label: 'Financeiro',  desc: 'Cobranças e honorários' },
                    { key: 'acessar_obrigacoes',  label: 'Obrigações',  desc: 'Vencimentos e calendário' },
                    { key: 'acessar_documentos',  label: 'Documentos',  desc: 'Arquivos e uploads' },
                ],
            },
        ],

        init() {},

        hasPerm(key) {
            return this.form.permissions.includes(key);
        },

        togglePerm(key) {
            const idx = this.form.permissions.indexOf(key);
            if (idx === -1) this.form.permissions.push(key);
            else this.form.permissions.splice(idx, 1);
        },

        checkedInGroup(group) {
            return group.perms.filter(p => this.form.permissions.includes(p.key)).length;
        },

        isGroupAll(group) {
            return group.perms.every(p => this.form.permissions.includes(p.key));
        },

        isGroupPartial(group) {
            const n = this.checkedInGroup(group);
            return n > 0 && n < group.perms.length;
        },

        toggleGroup(group, checked) {
            group.perms.forEach(p => {
                const idx = this.form.permissions.indexOf(p.key);
                if (checked && idx === -1) this.form.permissions.push(p.key);
                if (!checked && idx !== -1) this.form.permissions.splice(idx, 1);
            });
        },

        openCreate() {
            this.editId  = null;
            this.form    = { name: '', email: '', password: '', role: 'contador', permissions: [] };
            this.error   = '';
            this.modal   = true;
        },

        openEdit(id, name, email, role, permissions) {
            this.editId  = id;
            this.form    = { name, email, password: '', role, permissions: [...permissions] };
            this.error   = '';
            this.modal   = true;
        },

        async save() {
            this.saving = true;
            this.error  = '';
            const url    = this.editId ? '/admin/usuarios/' + this.editId : '/admin/usuarios';
            const method = this.editId ? 'PATCH' : 'POST';
            try {
                const res  = await fetch(url, {
                    method,
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content,
                    },
                    body: JSON.stringify(this.form),
                });
                const json = await res.json();
                if (!res.ok) {
                    this.error = json.message || Object.values(json.errors ?? {})[0]?.[0] || 'Erro ao salvar.';
                    return;
                }
                location.reload();
            } catch {
                this.error = 'Erro de conexão. Tente novamente.';
            } finally {
                this.saving = false;
            }
        },

        async deleteUser(id, name) {
            if (!confirm('Excluir o usuário "' + name + '"?\nEsta ação não pode ser desfeita.')) return;
            const res = await fetch('/admin/usuarios/' + id, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
            });
            if (res.ok) location.reload();
        },
    };
}
</script>
</x-admin-layout>
