<div class="space-y-5">
    <section class="rounded-lg border border-slate-200 bg-white p-5 shadow-soft dark:border-slate-800 dark:bg-slate-900">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            <div>
                <p class="text-xs font-semibold uppercase tracking-wide text-primary-600 dark:text-primary-300">Wiki Corporativa</p>
                <h1 class="mt-1 text-2xl font-bold text-slate-950 dark:text-white">Departamentos</h1>
                <p class="mt-2 text-sm leading-6 text-slate-600 dark:text-slate-400">Cadastre os departamentos que aparecerao na Wiki e escolha o icone exibido para cada um.</p>
            </div>

            <div class="flex flex-wrap items-center gap-2">
                <a href="{{ route('wiki.index') }}" class="btn-secondary">
                    <x-heroicon name="arrow-left" class="h-5 w-5" />
                    Voltar para Wiki
                </a>

                <button type="button" wire:click="abrirCriacao" class="btn-primary">
                    <x-heroicon name="plus" class="h-5 w-5" />
                    Novo departamento
                </button>
            </div>
        </div>

        <div class="mt-5">
            <label class="relative block max-w-xl">
                <x-heroicon name="magnifying-glass" class="pointer-events-none absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
                <input wire:model.debounce.350ms="busca" type="search" class="form-control pl-10" placeholder="Buscar departamento...">
            </label>
        </div>
    </section>

    <section class="rounded-lg border border-slate-200 bg-white shadow-soft dark:border-slate-800 dark:bg-slate-900">
        <div class="grid gap-3 p-4 lg:grid-cols-2 xl:grid-cols-3">
            @forelse ($departamentos as $departamento)
                <article class="rounded-lg border border-slate-200 bg-slate-50 p-4 transition hover:border-primary-300 dark:border-slate-800 dark:bg-slate-950/40 dark:hover:border-primary-700">
                    <div class="flex items-start gap-4">
                        <span class="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-accent-100 text-accent-700 dark:bg-slate-800 dark:text-accent-300">
                            <x-heroicon :name="$departamento->icone ?: 'building-office-2'" class="h-7 w-7" />
                        </span>

                        <div class="min-w-0 flex-1">
                            <div class="flex items-center justify-between gap-3">
                                <h2 class="truncate text-base font-bold text-slate-950 dark:text-white">{{ $departamento->nome }}</h2>
                                <x-badge :variant="$departamento->ativo ? 'success' : 'warning'">{{ $departamento->ativo ? 'Ativo' : 'Inativo' }}</x-badge>
                            </div>
                            <p class="mt-2 line-clamp-2 min-h-[2.5rem] text-sm leading-5 text-slate-600 dark:text-slate-400">{{ $departamento->descricao ?: 'Sem descricao cadastrada.' }}</p>

                            <div class="mt-3 grid grid-cols-3 gap-2 text-xs font-semibold text-slate-500 dark:text-slate-400">
                                <span class="rounded-lg border border-slate-200 px-2 py-1 dark:border-slate-800">{{ $departamento->usuarios_count }} usuarios</span>
                                <span class="rounded-lg border border-slate-200 px-2 py-1 dark:border-slate-800">{{ $departamento->subcategorias_count }} subcategorias</span>
                                <span class="rounded-lg border border-slate-200 px-2 py-1 dark:border-slate-800">{{ $departamento->artigos_count }} artigos</span>
                            </div>

                            <div class="mt-4 flex flex-wrap gap-2">
                                <button type="button" wire:click="editar({{ $departamento->id }})" class="btn-secondary px-3 py-1.5">
                                    Editar
                                </button>
                                <button type="button" wire:click="alternarAtivo({{ $departamento->id }})" class="btn-secondary px-3 py-1.5">
                                    {{ $departamento->ativo ? 'Inativar' : 'Ativar' }}
                                </button>
                                <button type="button"
                                        x-data
                                        x-on:click="if (confirm('Excluir este departamento? Usuarios vinculados ficarao sem departamento e artigos/subcategorias serao removidos.')) { $wire.excluir({{ $departamento->id }}) }"
                                        class="inline-flex items-center justify-center rounded-lg border border-rose-300 bg-white px-3 py-1.5 text-sm font-semibold text-rose-700 transition hover:bg-rose-50 dark:border-rose-800 dark:bg-slate-950 dark:text-rose-300 dark:hover:bg-rose-950/30">
                                    Excluir
                                </button>
                            </div>
                        </div>
                    </div>
                </article>
            @empty
                <div class="col-span-full rounded-lg border border-dashed border-slate-300 p-10 text-center dark:border-slate-700">
                    <h2 class="text-lg font-bold text-slate-950 dark:text-white">Nenhum departamento cadastrado</h2>
                    <p class="mt-2 text-sm text-slate-600 dark:text-slate-400">Crie o primeiro departamento para alimentar a entrada da Wiki.</p>
                </div>
            @endforelse
        </div>

        <div class="border-t border-slate-200 p-4 dark:border-slate-800">
            {{ $departamentos->links() }}
        </div>
    </section>

    @if ($modalAberto)
        <div class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/70 p-4 backdrop-blur-sm">
            <div class="max-h-[92vh] w-full max-w-5xl overflow-y-auto rounded-lg border border-slate-200 bg-white p-6 shadow-2xl dark:border-slate-800 dark:bg-slate-900">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h2 class="text-xl font-bold text-slate-950 dark:text-white">{{ $departamentoEditandoId ? 'Editar departamento' : 'Novo departamento' }}</h2>
                        <p class="mt-1 text-sm text-slate-600 dark:text-slate-400">O icone escolhido sera usado nos cards da Wiki.</p>
                    </div>
                    <button type="button" wire:click="$set('modalAberto', false)" class="rounded-lg p-2 text-slate-500 transition hover:bg-slate-100 dark:hover:bg-slate-800">Fechar</button>
                </div>

                <form wire:submit.prevent="salvar" class="mt-6 space-y-5">
                    <div class="grid gap-4 lg:grid-cols-[minmax(0,1fr)_280px]">
                        <div class="space-y-4">
                            <div>
                                <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Nome</label>
                                <input wire:model.defer="nome" type="text" class="form-control" maxlength="120">
                                <x-input-error :messages="$errors->get('nome')" />
                            </div>

                            <div>
                                <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Descricao</label>
                                <textarea wire:model.defer="descricao" rows="4" class="form-control"></textarea>
                                <x-input-error :messages="$errors->get('descricao')" />
                            </div>

                            <label class="flex items-center gap-3 rounded-lg border border-slate-200 px-4 py-3 text-sm font-semibold text-slate-700 dark:border-slate-800 dark:text-slate-200">
                                <input wire:model.defer="ativo" type="checkbox" class="rounded border-slate-300 text-primary-600 focus:ring-primary-500">
                                Departamento ativo
                            </label>
                        </div>

                        <div class="rounded-lg border border-slate-200 p-4 dark:border-slate-800">
                            <p class="text-sm font-bold text-slate-950 dark:text-white">Previa</p>
                            <div class="mt-4 rounded-lg border border-slate-200 bg-slate-50 p-4 dark:border-slate-800 dark:bg-slate-950">
                                <span class="flex h-14 w-14 items-center justify-center rounded-lg bg-accent-100 text-accent-700 dark:bg-slate-800 dark:text-accent-300">
                                    <x-heroicon :name="$icone" class="h-8 w-8" />
                                </span>
                                <p class="mt-3 text-sm font-bold text-slate-950 dark:text-white">{{ $nome ?: 'Nome do departamento' }}</p>
                                <p class="mt-1 text-xs text-slate-500 dark:text-slate-400">{{ $icone }}</p>
                            </div>
                        </div>
                    </div>

                    <div
                        x-data="{
                            buscaIcone: @entangle('buscaIcone').defer,
                            normalizar(valor) {
                                return (valor || '').toString().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[_\-\/.,]/g, ' ').replace(/\s+/g, ' ').trim().toLowerCase();
                            },
                            exibe(rotulo) {
                                const busca = this.normalizar(this.buscaIcone);
                                return busca === '' || this.normalizar(rotulo).includes(busca);
                            }
                        }"
                        class="rounded-lg border border-slate-200 p-4 dark:border-slate-800"
                    >
                        <div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
                            <div>
                                <label class="block text-sm font-bold text-slate-950 dark:text-white">Icone Heroicons 2</label>
                                <p class="mt-1 text-xs text-slate-500 dark:text-slate-400">Busque por nome em ingles ou termo em portugues. Ex: transporte, financeiro, usuarios, documento.</p>
                            </div>
                            <label class="relative w-full md:max-w-sm">
                                <x-heroicon name="magnifying-glass" class="pointer-events-none absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
                                <input x-model.debounce.150ms="buscaIcone" wire:model.debounce.250ms="buscaIcone" type="search" class="form-control pl-10" placeholder="Buscar entre {{ $totalIcones }} icones...">
                            </label>
                        </div>

                        <div class="sidebar-scroll mt-4 grid max-h-72 grid-cols-2 gap-2 overflow-y-auto pr-1 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6">
                            @forelse ($icones as $iconeItem)
                                <button
                                    type="button"
                                    wire:click="selecionarIcone('{{ $iconeItem }}')"
                                    x-show="exibe(@js($iconeItem . ' ' . ($rotulosIcones[$iconeItem] ?? '')))"
                                    @class([
                                    'flex items-center gap-2 rounded-lg border px-3 py-2 text-left text-xs font-semibold transition',
                                    'border-primary-400 bg-primary-50 text-primary-700 dark:border-primary-700 dark:bg-primary-950/50 dark:text-primary-200' => $icone === $iconeItem,
                                    'border-slate-200 text-slate-600 hover:border-primary-300 hover:bg-primary-50 dark:border-slate-800 dark:text-slate-300 dark:hover:border-primary-700 dark:hover:bg-primary-950/30' => $icone !== $iconeItem,
                                ])>
                                    <x-heroicon :name="$iconeItem" class="h-5 w-5 shrink-0" />
                                    <span class="truncate">{{ $iconeItem }}</span>
                                </button>
                            @empty
                                <div class="col-span-full rounded-lg border border-dashed border-slate-300 p-6 text-center text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">
                                    Nenhum icone encontrado. Tente buscar por um termo em ingles ou por palavras como transporte, financeiro, usuarios, documento ou rastreamento.
                                </div>
                            @endforelse
                        </div>

                        <x-input-error :messages="$errors->get('icone')" />
                    </div>

                    <div class="flex justify-end gap-3 border-t border-slate-200 pt-5 dark:border-slate-800">
                        <button type="button" wire:click="$set('modalAberto', false)" class="btn-secondary">Cancelar</button>
                        <button type="submit" class="btn-primary">Salvar departamento</button>
                    </div>
                </form>
            </div>
        </div>
    @endif
</div>
