<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 xl:flex-row xl:items-center xl:justify-between">
            <div class="min-w-0">
                <div class="flex flex-wrap items-center gap-3">
                    <span class="inline-flex h-11 w-11 items-center justify-center rounded-lg bg-accent-100 text-accent-700 dark:bg-slate-800 dark:text-accent-300">
                        @if ($departamentoSelecionado)
                            <x-heroicon :name="$departamentoSelecionado->icone ?: 'building-office-2'" class="h-7 w-7" />
                        @else
                            <x-heroicon name="book-open" class="h-7 w-7" />
                        @endif
                    </span>
                    <div>
                        <p class="text-xs font-semibold uppercase tracking-wide text-primary-600 dark:text-primary-300">Wiki Corporativa</p>
                        <h1 class="text-2xl font-bold text-slate-950 dark:text-white">
                            @if ($subcategoriaSelecionada)
                                {{ $subcategoriaSelecionada->nome }}
                            @elseif ($departamentoSelecionado)
                                {{ $departamentoSelecionado->nome }}
                            @else
                                Departamentos
                            @endif
                        </h1>
                    </div>
                </div>

                <p class="mt-3 max-w-3xl text-sm leading-6 text-slate-600 dark:text-slate-400">
                    @if ($subcategoriaSelecionada)
                        Artigos de {{ $departamentoSelecionado->nome }} agrupados em {{ $subcategoriaSelecionada->nome }}.
                    @elseif ($departamentoSelecionado)
                        {{ $departamentoSelecionado->descricao ?: 'Selecione uma subcategoria para visualizar os artigos.' }}
                    @else
                        Escolha um departamento cadastrado pelo Administrador Master para acessar subcategorias e artigos.
                    @endif
                </p>
            </div>

            <div class="flex flex-wrap items-center gap-2">
                @if (! $departamentoSelecionado && $podeGerenciarDepartamentos)
                    <a href="{{ route('wiki.departamentos') }}" class="btn-primary">
                        <x-heroicon name="building-office-2" class="h-5 w-5" />
                        Gerenciar departamentos
                    </a>
                @endif

                @if ($departamentoSelecionado)
                    <a href="{{ route('wiki.index') }}" class="btn-secondary">
                        <x-heroicon name="arrow-left" class="h-5 w-5" />
                        Departamentos
                    </a>
                @endif

                @if ($departamentoSelecionado)
                    @livewire('wiki.subcategoria-manager', ['departamentoId' => $departamentoSelecionado->id], key('subcategorias-'.$departamentoSelecionado->id))
                @endif

                @if ($subcategoriaSelecionada)
                    @can('wiki.criar')
                        <button type="button" wire:click="abrirCriacao" class="btn-primary">
                            <x-heroicon name="document-plus" class="h-5 w-5" />
                            Novo artigo
                        </button>
                    @endcan
                @endif
            </div>
        </div>
    </section>

    @if (! $departamentoSelecionado)
        @include('livewire.wiki.partials.departamentos-grid', [
            'departamentos' => $departamentos,
            'podeGerenciarDepartamentos' => $podeGerenciarDepartamentos,
        ])
    @elseif (! $subcategoriaSelecionada)
        @include('livewire.wiki.partials.subcategorias-grid', ['departamento' => $departamentoSelecionado, 'subcategorias' => $subcategorias])
    @else
        <section class="rounded-lg border border-slate-200 bg-white p-4 shadow-soft dark:border-slate-800 dark:bg-slate-900">
            <div class="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
                <div class="flex flex-wrap items-center gap-2 text-sm font-semibold text-slate-500 dark:text-slate-400">
                    <a href="{{ route('wiki.index') }}" class="text-primary-600 transition hover:text-primary-700 dark:text-primary-300">Departamentos</a>
                    <span>/</span>
                    <a href="{{ route('wiki.departamento', $departamentoSelecionado->slug) }}" class="text-primary-600 transition hover:text-primary-700 dark:text-primary-300">{{ $departamentoSelecionado->nome }}</a>
                    <span>/</span>
                    <span class="text-slate-700 dark:text-slate-200">{{ $subcategoriaSelecionada->nome }}</span>
                </div>

                <div class="grid w-full gap-3 xl:w-auto xl:grid-cols-[360px_180px]">
                    <label class="relative">
                        <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.450ms="busca" type="search" class="form-control pl-10" placeholder="Buscar artigos...">
                    </label>

                    <select wire:model="ordenacao" class="form-control">
                        <option value="recentes">Recentes</option>
                        <option value="populares">Mais acessados</option>
                        <option value="uteis">Melhor avaliados</option>
                    </select>
                </div>
            </div>
        </section>

        <section class="grid gap-4 xl:min-h-[30rem] xl:grid-cols-[390px_minmax(0,1fr)]">
            <aside class="flex min-h-0 flex-col rounded-lg border border-slate-200 bg-white shadow-soft dark:border-slate-800 dark:bg-slate-900">
                <div class="border-b border-slate-200 p-4 dark:border-slate-800">
                    <div class="flex items-center justify-between gap-3">
                        <div>
                            <h2 class="text-sm font-bold text-slate-950 dark:text-white">Artigos</h2>
                            <p class="mt-1 text-xs text-slate-500 dark:text-slate-400">{{ $subcategoriaSelecionada->nome }} / {{ $departamentoSelecionado->nome }}</p>
                        </div>
                        <div wire:loading class="text-xs font-semibold text-primary-600 dark:text-primary-300">Atualizando...</div>
                    </div>
                </div>

                <div wire:loading.class="opacity-60" class="sidebar-scroll min-h-0 flex-1 space-y-2 overflow-y-auto p-3">
                    @forelse ($artigos as $artigo)
                        @php
                            $favoritado = $artigo->favoritos->where('user_id', auth()->id())->isNotEmpty();
                            $pontuacao = (int) ($artigo->votos_sum_valor ?? 0);
                            $selecionado = (int) $artigoSelecionadoId === (int) $artigo->id;
                        @endphp

                        <article @class([
                            'rounded-lg border bg-white p-3 transition dark:bg-slate-950/50',
                            'border-primary-300 shadow-sm dark:border-primary-700' => $selecionado,
                            'border-slate-200 hover:border-primary-300 hover:bg-primary-50/40 dark:border-slate-800 dark:hover:border-primary-700 dark:hover:bg-primary-950/20' => ! $selecionado,
                        ])>
                            <div class="flex items-start justify-between gap-3">
                                <button type="button" wire:click="selecionar({{ $artigo->id }})" class="min-w-0 flex-1 text-left">
                                    <div class="flex flex-wrap gap-1.5">
                                        <x-badge variant="primary">{{ $artigo->subcategoria->nome ?? $artigo->categoria->nome ?? 'Sem subcategoria' }}</x-badge>
                                        <x-badge>{{ $artigo->departamento->nome }}</x-badge>
                                    </div>

                                    <h3 class="mt-3 line-clamp-2 text-sm font-bold leading-5 text-slate-950 transition hover:text-primary-700 dark:text-white dark:hover:text-primary-300">
                                        {{ $artigo->titulo }}
                                    </h3>
                                    <p class="mt-2 line-clamp-2 text-xs leading-5 text-slate-600 dark:text-slate-400">
                                        {{ Str::limit(strip_tags($artigo->conteudo), 118) }}
                                    </p>
                                </button>

                                <button type="button" wire:click="favoritar({{ $artigo->id }})" class="shrink-0 rounded-lg p-1.5 text-slate-400 transition hover:bg-rose-50 hover:text-rose-500 dark:hover:bg-rose-950/30" title="Favoritar">
                                    <x-heroicon name="heart" @class(['h-5 w-5', 'fill-rose-500 text-rose-500' => $favoritado]) />
                                </button>
                            </div>

                            <div class="mt-3 flex flex-wrap items-center justify-between gap-2 border-t border-slate-200 pt-3 text-xs font-semibold text-slate-500 dark:border-slate-800 dark:text-slate-400">
                                <span class="inline-flex items-center gap-1">
                                    <x-heroicon name="eye" class="h-4 w-4" />
                                    {{ $artigo->visualizacoes_count }}
                                </span>
                                <span class="inline-flex items-center gap-1">
                                    <x-heroicon name="hand-thumb-up" class="h-4 w-4" />
                                    {{ $pontuacao }}
                                </span>
                                <span class="truncate">{{ $artigo->updated_at->format('d/m/Y') }}</span>
                            </div>
                        </article>
                    @empty
                        <div class="rounded-lg border border-dashed border-slate-300 p-6 text-center dark:border-slate-700">
                            <h3 class="text-sm font-bold text-slate-950 dark:text-white">Nenhum artigo encontrado</h3>
                            <p class="mt-2 text-xs leading-5 text-slate-600 dark:text-slate-400">Crie o primeiro artigo ou ajuste a busca.</p>
                        </div>
                    @endforelse
                </div>

                <div class="shrink-0 border-t border-slate-200 p-3 dark:border-slate-800">
                    {{ $artigos->links() }}
                </div>
            </aside>

            <main class="flex min-h-0 min-w-0 flex-col rounded-lg border border-slate-200 bg-white shadow-soft dark:border-slate-800 dark:bg-slate-900">
                @if ($artigoSelecionado)
                    @php
                        $votoUsuario = $artigoSelecionado->votoDoUsuario();
                        $pontuacaoSelecionada = (int) ($artigoSelecionado->votos_sum_valor ?? 0);
                        $videosDoArtigo = $artigoSelecionado->anexos->where('tipo', 'video');
                        $imagensDoArtigo = $artigoSelecionado->anexos->where('tipo', 'imagem');
                        $totalAnexosArtigo = $artigoSelecionado->anexos->count();
                    @endphp

                    <div wire:key="artigo-detalhe-{{ $artigoSelecionado->id }}" x-data="{ abaWiki: 'conteudo' }" class="flex min-h-[30rem] flex-1 flex-col xl:min-h-0">
                        <header class="border-b border-slate-200 p-4 dark:border-slate-800">
                            <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                                <div class="min-w-0">
                                    <div class="flex flex-wrap gap-2">
                                        <x-badge variant="primary">{{ $artigoSelecionado->subcategoria->nome ?? $subcategoriaSelecionada->nome }}</x-badge>
                                        <x-badge>{{ $artigoSelecionado->departamento->nome }}</x-badge>
                                        <x-badge :variant="$artigoSelecionado->status === 'publicado' ? 'success' : 'warning'">{{ ucfirst($artigoSelecionado->status) }}</x-badge>
                                        @if ($artigoSelecionado->restrito)
                                            <x-badge variant="warning">Restrito</x-badge>
                                        @endif
                                    </div>

                                    <h2 class="mt-3 text-2xl font-bold leading-tight text-slate-950 dark:text-white">{{ $artigoSelecionado->titulo }}</h2>

                                    <div class="mt-4 flex flex-wrap items-center gap-3 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 dark:border-slate-800 dark:bg-slate-950/60">
                                        <x-user-avatar :user="$artigoSelecionado->autor" size="sm" />
                                        <div class="min-w-0">
                                            <p class="text-sm font-bold text-slate-950 dark:text-white">
                                                {{ $artigoSelecionado->autor->name }}
                                            </p>
                                            <p class="text-xs text-slate-500 dark:text-slate-400">
                                                Criou este tutorial em {{ $artigoSelecionado->created_at->format('d/m/Y') }}. Atualizado em {{ $artigoSelecionado->updated_at->format('d/m/Y H:i') }}.
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                <div class="flex shrink-0 flex-wrap items-center gap-2">
                                    @can('wiki.editar')
                                        @if ($this->usuarioPodeEditar($artigoSelecionado))
                                            <button type="button" wire:click="editar({{ $artigoSelecionado->id }})" class="btn-secondary px-3">
                                                Editar
                                            </button>
                                        @endif
                                    @endcan
                                </div>
                            </div>

                            <div class="mt-4 flex flex-wrap items-center gap-2 text-xs font-semibold text-slate-500 dark:text-slate-400">
                                <span class="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 px-3 py-2 dark:border-slate-800">
                                    <x-heroicon name="eye" class="h-4 w-4" />
                                    {{ $artigoSelecionado->visualizacoes_count }} acessos
                                </span>
                                <span class="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 px-3 py-2 dark:border-slate-800">
                                    <x-heroicon name="hand-thumb-up" class="h-4 w-4" />
                                    {{ $pontuacaoSelecionada }} utilidade
                                </span>
                                <button type="button" wire:click="votar({{ $artigoSelecionado->id }}, 1)" @class([
                                    'inline-flex items-center gap-1.5 rounded-lg border px-3 py-2 transition',
                                    'border-emerald-400 bg-emerald-50 text-emerald-700 dark:border-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-200' => optional($votoUsuario)->valor === 1,
                                    'border-slate-200 text-slate-500 hover:border-emerald-300 hover:bg-emerald-50 dark:border-slate-800 dark:text-slate-300 dark:hover:border-emerald-700 dark:hover:bg-emerald-950/30' => optional($votoUsuario)->valor !== 1,
                                ])>
                                    <x-heroicon name="hand-thumb-up" class="h-4 w-4" />
                                    Util
                                </button>
                                <button type="button" wire:click="votar({{ $artigoSelecionado->id }}, -1)" @class([
                                    'inline-flex items-center gap-1.5 rounded-lg border px-3 py-2 transition',
                                    'border-rose-400 bg-rose-50 text-rose-700 dark:border-rose-700 dark:bg-rose-950/50 dark:text-rose-200' => optional($votoUsuario)->valor === -1,
                                    'border-slate-200 text-slate-500 hover:border-rose-300 hover:bg-rose-50 dark:border-slate-800 dark:text-slate-300 dark:hover:border-rose-700 dark:hover:bg-rose-950/30' => optional($votoUsuario)->valor !== -1,
                                ])>
                                    <x-heroicon name="hand-thumb-down" class="h-4 w-4" />
                                    Nao util
                                </button>
                            </div>
                        </header>

                        <nav class="flex gap-1 overflow-x-auto border-b border-slate-200 px-4 py-2 dark:border-slate-800">
                            @php
                                $abasWiki = [
                                    'conteudo' => 'Conteudo',
                                    'anexos' => 'Anexos' . ($totalAnexosArtigo ? " ({$totalAnexosArtigo})" : ''),
                                    'versoes' => 'Versoes',
                                    'comentarios' => 'Comentarios',
                                    'relacionados' => 'Relacionados',
                                ];
                            @endphp

                            @foreach ($abasWiki as $aba => $rotulo)
                                <button type="button" x-on:click="abaWiki = '{{ $aba }}'" :class="abaWiki === '{{ $aba }}' ? 'bg-primary-600 text-white' : 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800'" class="rounded-lg px-3 py-2 text-sm font-semibold transition">
                                    {{ $rotulo }}
                                </button>
                            @endforeach
                        </nav>

                        <div class="sidebar-scroll min-h-0 flex-1 overflow-y-auto p-4 lg:p-5">
                            <div x-show="abaWiki === 'conteudo'" x-cloak>
                                @if ($videosDoArtigo->isNotEmpty())
                                    <div class="mb-5 rounded-lg border border-accent-300 bg-accent-50 p-4 dark:border-accent-800 dark:bg-accent-950/30">
                                        <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                                            <div class="flex items-start gap-3">
                                                <span class="flex h-11 w-11 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="play-circle" class="h-7 w-7" />
                                                </span>
                                                <div>
                                                    <h3 class="text-sm font-bold text-slate-950 dark:text-white">Este tutorial possui video de apoio</h3>
                                                    <p class="mt-1 text-sm leading-6 text-slate-700 dark:text-slate-300">
                                                        Assista {{ $videosDoArtigo->count() === 1 ? 'ao video' : 'aos videos' }} antes ou durante a leitura para acompanhar a documentacao com mais clareza.
                                                    </p>
                                                </div>
                                            </div>

                                            <button type="button" x-on:click="abaWiki = 'anexos'" class="btn-primary shrink-0">
                                                <x-heroicon name="play" class="h-5 w-5" />
                                                Ver video
                                            </button>
                                        </div>
                                    </div>
                                @elseif ($totalAnexosArtigo > 0)
                                    <div class="mb-5 flex flex-col gap-3 rounded-lg border border-slate-200 bg-slate-50 p-4 dark:border-slate-800 dark:bg-slate-950/60 sm:flex-row sm:items-center sm:justify-between">
                                        <div class="flex items-center gap-3">
                                            <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300">
                                                <x-heroicon name="paper-clip" class="h-6 w-6" />
                                            </span>
                                            <p class="text-sm font-semibold text-slate-700 dark:text-slate-200">
                                                Este artigo possui {{ $totalAnexosArtigo }} {{ $totalAnexosArtigo === 1 ? 'anexo' : 'anexos' }} complementar(es).
                                            </p>
                                        </div>

                                        <button type="button" x-on:click="abaWiki = 'anexos'" class="btn-secondary shrink-0">
                                            Ver anexos
                                        </button>
                                    </div>
                                @endif

                                <div class="wiki-content max-w-none">
                                    {!! $artigoSelecionado->conteudo !!}
                                </div>
                            </div>

                            <div x-show="abaWiki === 'anexos'" x-cloak>
                                <div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
                                    <div>
                                        <h3 class="text-sm font-bold text-slate-950 dark:text-white">Imagens, videos e anexos</h3>
                                        @if ($videosDoArtigo->isNotEmpty())
                                            <p class="mt-1 text-xs font-semibold text-accent-700 dark:text-accent-300">
                                                {{ $videosDoArtigo->count() }} {{ $videosDoArtigo->count() === 1 ? 'video disponivel' : 'videos disponiveis' }} para acompanhar este tutorial.
                                            </p>
                                        @endif
                                    </div>

                                    @if ($imagensDoArtigo->isNotEmpty() || $videosDoArtigo->isNotEmpty())
                                        <div class="flex flex-wrap gap-2 text-xs font-semibold text-slate-500 dark:text-slate-400">
                                            @if ($videosDoArtigo->isNotEmpty())
                                                <span class="rounded-full border border-accent-300 px-2.5 py-1 text-accent-700 dark:border-accent-800 dark:text-accent-300">{{ $videosDoArtigo->count() }} video(s)</span>
                                            @endif
                                            @if ($imagensDoArtigo->isNotEmpty())
                                                <span class="rounded-full border border-slate-200 px-2.5 py-1 dark:border-slate-800">{{ $imagensDoArtigo->count() }} imagem(ns)</span>
                                            @endif
                                        </div>
                                    @endif
                                </div>

                                @if ($artigoSelecionado->anexos->isNotEmpty())
                                    <div class="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                                        @foreach ($artigoSelecionado->anexos as $anexo)
                                            @php($anexoUrl = route('wiki.anexos.visualizar', $anexo))

                                            <div class="rounded-lg border border-slate-200 p-3 text-sm transition hover:border-primary-300 dark:border-slate-800 dark:hover:border-primary-700">
                                                @if ($anexo->tipo === 'imagem')
                                                    <img src="{{ $anexoUrl }}" alt="{{ $anexo->nome_original }}" class="mb-3 h-36 w-full rounded-lg object-cover">
                                                @elseif ($anexo->tipo === 'video')
                                                    <video controls preload="metadata" class="mb-3 h-36 w-full rounded-lg bg-slate-950 object-contain">
                                                        <source src="{{ $anexoUrl }}" type="{{ $anexo->mime ?: 'video/mp4' }}">
                                                        Seu navegador nao suporta a visualizacao deste video.
                                                    </video>
                                                @else
                                                    <div class="mb-3 flex h-36 w-full items-center justify-center rounded-lg border border-dashed border-slate-300 bg-slate-50 text-slate-500 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-400">
                                                        <x-heroicon name="paper-clip" class="h-8 w-8" />
                                                    </div>
                                                @endif
                                                <span class="font-semibold text-slate-900 dark:text-white">{{ $anexo->nome_original }}</span>
                                                <span class="mt-1 block text-xs text-slate-500 dark:text-slate-400">
                                                    {{ ucfirst($anexo->tipo) }} / {{ number_format($anexo->tamanho / 1024, 1, ',', '.') }} KB
                                                </span>
                                                <a href="{{ $anexoUrl }}" target="_blank" class="mt-3 inline-flex items-center gap-1 text-xs font-bold text-primary-600 transition hover:text-primary-700 dark:text-primary-300">
                                                    Abrir arquivo
                                                    <x-heroicon name="arrow-top-right-on-square" class="h-4 w-4" />
                                                </a>
                                            </div>
                                        @endforeach
                                    </div>
                                @else
                                    <p class="mt-4 rounded-lg border border-dashed border-slate-300 p-6 text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">Este artigo ainda nao possui imagens, videos ou anexos.</p>
                                @endif
                            </div>

                            <div x-show="abaWiki === 'versoes'" x-cloak>
                                <h3 class="text-sm font-bold text-slate-950 dark:text-white">Historico de versoes</h3>
                                <div class="mt-4 space-y-3">
                                    @forelse ($artigoSelecionado->versoes->sortByDesc('versao') as $versao)
                                        <div class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-800 dark:bg-slate-950">
                                            <div class="flex items-start gap-3">
                                                <x-user-avatar :user="$versao->usuario" size="sm" />

                                                <div class="min-w-0 flex-1">
                                                    <div class="flex flex-wrap justify-between gap-3 font-semibold text-slate-800 dark:text-slate-200">
                                                        <span>Versao {{ $versao->versao }}</span>
                                                        <span>{{ $versao->created_at->format('d/m/Y H:i') }}</span>
                                                    </div>

                                                    <p class="mt-1 text-xs text-slate-500 dark:text-slate-400">
                                                        Alterado por <span class="font-semibold text-slate-700 dark:text-slate-200">{{ $versao->usuario->name ?? 'Usuario removido' }}</span>
                                                    </p>

                                                    <p class="mt-2 text-slate-500 dark:text-slate-400">{{ $versao->resumo_alteracoes }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    @empty
                                        <p class="rounded-lg border border-dashed border-slate-300 p-6 text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">Nenhuma versao registrada.</p>
                                    @endforelse
                                </div>
                            </div>

                            <div x-show="abaWiki === 'comentarios'" x-cloak>
                                <h3 class="text-sm font-bold text-slate-950 dark:text-white">Comentarios internos</h3>
                                <div class="mt-4 space-y-3">
                                    @forelse ($artigoSelecionado->comentarios as $comentarioItem)
                                        <div class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-sm dark:border-slate-800 dark:bg-slate-950">
                                            <div class="flex items-start gap-3">
                                                <x-user-avatar :user="$comentarioItem->usuario" size="sm" />
                                                <div class="min-w-0 flex-1">
                                                    <div class="flex flex-wrap justify-between gap-3 text-xs font-semibold text-slate-500 dark:text-slate-400">
                                                        <span class="text-slate-800 dark:text-slate-100">{{ $comentarioItem->usuario->name }}</span>
                                                        <span>{{ $comentarioItem->created_at->diffForHumans() }}</span>
                                                    </div>
                                                    <p class="mt-2 text-slate-700 dark:text-slate-200">{{ $comentarioItem->conteudo }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    @empty
                                        <p class="rounded-lg border border-dashed border-slate-300 p-6 text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">Nenhum comentario publicado.</p>
                                    @endforelse
                                </div>

                                @can('wiki.comentar')
                                    <form wire:submit.prevent="comentar" class="mt-4 space-y-3">
                                        <textarea wire:model.defer="comentario" rows="3" class="form-control" placeholder="Escreva um comentario interno..."></textarea>
                                        <x-input-error :messages="$errors->get('comentario')" />
                                        <button type="submit" class="btn-primary w-full sm:w-auto">Publicar comentario</button>
                                    </form>
                                @endcan
                            </div>

                            <div x-show="abaWiki === 'relacionados'" x-cloak>
                                <h3 class="text-sm font-bold text-slate-950 dark:text-white">Artigos relacionados</h3>

                                @if ($artigosRelacionados->isNotEmpty())
                                    <div class="mt-4 grid gap-3 md:grid-cols-2">
                                        @foreach ($artigosRelacionados as $relacionado)
                                            <button type="button" wire:click="selecionar({{ $relacionado->id }})" class="rounded-lg border border-slate-200 p-4 text-left transition hover:border-primary-300 hover:bg-primary-50/60 dark:border-slate-800 dark:hover:border-primary-700 dark:hover:bg-primary-950/30">
                                                <span class="block text-sm font-semibold text-slate-800 dark:text-slate-100">{{ $relacionado->titulo }}</span>
                                                <span class="mt-2 inline-flex items-center gap-1 text-xs text-slate-500 dark:text-slate-400">
                                                    <x-heroicon name="eye" class="h-4 w-4" />
                                                    {{ $relacionado->visualizacoes_count }} acessos
                                                </span>
                                            </button>
                                        @endforeach
                                    </div>
                                @else
                                    <p class="mt-4 rounded-lg border border-dashed border-slate-300 p-6 text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">Nao ha artigos relacionados nesta subcategoria.</p>
                                @endif
                            </div>
                        </div>
                    </div>
                @else
                    <div class="grid min-h-[30rem] flex-1 gap-0 xl:grid-cols-[minmax(0,1fr)_320px]">
                        <div class="flex items-center justify-center p-6 text-center">
                            <div class="max-w-md">
                                <div class="mx-auto flex h-16 w-16 items-center justify-center rounded-lg bg-accent-50 text-accent-700 dark:bg-slate-800 dark:text-accent-300">
                                    <x-heroicon name="book-open" class="h-8 w-8" />
                                </div>
                                <h2 class="mt-5 text-xl font-bold text-slate-950 dark:text-white">Selecione um artigo</h2>
                                <p class="mt-2 text-sm leading-6 text-slate-600 dark:text-slate-400">A leitura, anexos, versoes, comentarios e artigos relacionados aparecem neste painel.</p>
                            </div>
                        </div>

                        <aside class="border-t border-slate-200 p-4 dark:border-slate-800 xl:border-l xl:border-t-0">
                            <div>
                                <div class="flex items-center justify-between gap-3">
                                    <h3 class="text-sm font-bold text-slate-950 dark:text-white">Mais acessados</h3>
                                    <x-heroicon name="eye" class="h-5 w-5 text-accent-600 dark:text-accent-300" />
                                </div>
                                <div class="mt-3 space-y-2">
                                    @forelse ($maisAcessados as $item)
                                        <button type="button" wire:click="selecionar({{ $item->id }})" class="flex w-full items-center justify-between gap-3 rounded-lg border border-slate-200 px-3 py-2 text-left transition hover:border-primary-300 hover:bg-primary-50/60 dark:border-slate-800 dark:hover:border-primary-700 dark:hover:bg-primary-950/30">
                                            <span class="min-w-0">
                                                <span class="block truncate text-sm font-semibold text-slate-800 dark:text-slate-100">{{ $item->titulo }}</span>
                                                <span class="block truncate text-xs text-slate-500 dark:text-slate-400">{{ $item->subcategoria->nome ?? 'Sem subcategoria' }}</span>
                                            </span>
                                            <span class="inline-flex shrink-0 items-center gap-1 text-xs font-semibold text-slate-500 dark:text-slate-400">
                                                <x-heroicon name="eye" class="h-4 w-4" />
                                                {{ $item->visualizacoes_count }}
                                            </span>
                                        </button>
                                    @empty
                                        <p class="rounded-lg border border-dashed border-slate-300 p-4 text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">Os acessos aparecerao conforme os artigos forem abertos.</p>
                                    @endforelse
                                </div>
                            </div>

                            <div class="mt-6">
                                <div class="flex items-center justify-between gap-3">
                                    <h3 class="text-sm font-bold text-slate-950 dark:text-white">Buscas frequentes</h3>
                                    <x-heroicon name="sparkles" class="h-5 w-5 text-accent-500 dark:text-accent-300" />
                                </div>
                                <div class="mt-3 flex flex-wrap gap-2">
                                    @forelse ($termosBuscados as $termo)
                                        <button type="button" wire:click="$set('busca', @js($termo->termo))" class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600 transition hover:border-accent-300 hover:bg-accent-50 dark:border-slate-800 dark:text-slate-300 dark:hover:border-accent-700 dark:hover:bg-accent-950/30">
                                            {{ $termo->termo }}
                                            <span class="ml-1 text-slate-400">({{ $termo->total }})</span>
                                        </button>
                                    @empty
                                        <p class="rounded-lg border border-dashed border-slate-300 p-4 text-sm text-slate-500 dark:border-slate-700 dark:text-slate-400">As pesquisas da Wiki serao registradas para melhorar a curadoria interna.</p>
                                    @endforelse
                                </div>
                            </div>
                        </aside>
                    </div>
                @endif
            </main>
        </section>
    @endif

    @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-4xl 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">{{ $artigoEditandoId ? 'Editar artigo' : 'Novo artigo' }}</h2>
                        <p class="mt-1 text-sm text-slate-600 dark:text-slate-400">Use o editor para manter processos e procedimentos bem documentados.</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 md:grid-cols-2">
                        <div class="md:col-span-2">
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Titulo</label>
                            <input wire:model.defer="titulo" type="text" class="form-control" maxlength="180">
                            <x-input-error :messages="$errors->get('titulo')" />
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Departamento</label>
                            <input type="text" class="form-control" value="{{ $departamentoSelecionado->nome ?? '' }}" disabled>
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Subcategoria</label>
                            <select wire:model.defer="subcategoria_id" class="form-control">
                                @foreach ($subcategoriasFormulario as $subcategoriaFormulario)
                                    <option value="{{ $subcategoriaFormulario->id }}">{{ $subcategoriaFormulario->nome }}</option>
                                @endforeach
                            </select>
                            <x-input-error :messages="$errors->get('subcategoria_id')" />
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Status</label>
                            <select wire:model.defer="status" class="form-control">
                                <option value="rascunho">Rascunho</option>
                                <option value="publicado">Publicado</option>
                            </select>
                        </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="restrito" type="checkbox" class="rounded border-slate-300 text-primary-600 focus:ring-primary-500">
                            Restrito ao departamento
                        </label>
                    </div>

                    <div wire:ignore>
                        <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Conteudo</label>
                        <div id="editor-wiki"></div>
                    </div>
                    <input type="hidden" wire:model.defer="conteudo" id="conteudo-wiki">
                    <x-input-error :messages="$errors->get('conteudo')" />

                    <div>
                        <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Imagens, videos e anexos</label>
                        <input wire:model="novosAnexos" type="file" multiple accept="image/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar" class="form-control">
                        <p class="mt-2 text-xs text-slate-500 dark:text-slate-400">Cole imagens direto no editor ou use este campo para anexar imagens, videos e documentos. Videos aparecem com player na aba Anexos.</p>
                        <x-input-error :messages="$errors->get('novosAnexos.*')" />

                        @if ($novosAnexos)
                            <div class="mt-3 grid gap-2 sm:grid-cols-2">
                                @foreach ($novosAnexos as $arquivo)
                                    <div class="rounded-lg bg-slate-50 p-3 text-xs text-slate-600 dark:bg-slate-950 dark:text-slate-300">{{ $arquivo->getClientOriginalName() }}</div>
                                @endforeach
                            </div>
                        @endif
                    </div>

                    <div>
                        <label class="mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200">Resumo das alteracoes</label>
                        <input wire:model.defer="resumoAlteracoes" type="text" class="form-control" placeholder="Ex: Revisao do procedimento de embarque">
                    </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 artigo</button>
                    </div>
                </form>
            </div>
        </div>
    @endif

    @push('scripts')
        <script>
            document.addEventListener('livewire:load', () => {
                let quill = null;
                const uploadUrl = @js(route('wiki.editor-upload'));
                const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

                const inserirImagem = async (arquivo, editorQuill) => {
                    const formData = new FormData();
                    formData.append('arquivo', arquivo);

                    const response = await fetch(uploadUrl, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': csrfToken,
                            'Accept': 'application/json',
                        },
                        body: formData,
                    });

                    if (!response.ok) {
                        window.dispatchEvent(new CustomEvent('notify', {
                            detail: { message: 'Nao foi possivel enviar a imagem.' },
                        }));
                        return;
                    }

                    const data = await response.json();
                    const range = editorQuill.getSelection(true);
                    editorQuill.insertEmbed(range.index, 'image', data.url, 'user');
                    editorQuill.setSelection(range.index + 1, 0, 'silent');
                    @this.set('conteudo', editorQuill.root.innerHTML);
                };

                Livewire.hook('message.processed', () => {
                    const editor = document.getElementById('editor-wiki');
                    const input = document.getElementById('conteudo-wiki');

                    if (!editor || !input) {
                        quill = null;
                        return;
                    }

                    if (quill) {
                        return;
                    }

                    quill = new Quill(editor, {
                        theme: 'snow',
                        modules: {
                            toolbar: {
                                container: [
                                    [{ header: [1, 2, 3, false] }],
                                    ['bold', 'italic', 'underline', 'strike'],
                                    [{ list: 'ordered' }, { list: 'bullet' }],
                                    ['blockquote', 'code-block', 'link', 'image'],
                                    ['clean'],
                                ],
                                handlers: {
                                    image: function () {
                                        const fileInput = document.createElement('input');
                                        fileInput.setAttribute('type', 'file');
                                        fileInput.setAttribute('accept', 'image/*');
                                        fileInput.click();

                                        fileInput.onchange = async () => {
                                            const arquivo = fileInput.files[0];

                                            if (arquivo) {
                                                await inserirImagem(arquivo, quill);
                                            }
                                        };
                                    },
                                },
                            },
                        },
                    });

                    quill.root.innerHTML = @this.get('conteudo') || '';
                    quill.on('text-change', () => {
                        @this.set('conteudo', quill.root.innerHTML);
                    });

                    quill.root.addEventListener('paste', async (event) => {
                        const arquivos = Array.from(event.clipboardData?.files || [])
                            .filter((arquivo) => arquivo.type.startsWith('image/'));

                        if (!arquivos.length) {
                            return;
                        }

                        event.preventDefault();

                        for (const arquivo of arquivos) {
                            await inserirImagem(arquivo, quill);
                        }
                    });

                    quill.root.addEventListener('drop', async (event) => {
                        const arquivos = Array.from(event.dataTransfer?.files || [])
                            .filter((arquivo) => arquivo.type.startsWith('image/'));

                        if (!arquivos.length) {
                            return;
                        }

                        event.preventDefault();

                        for (const arquivo of arquivos) {
                            await inserirImagem(arquivo, quill);
                        }
                    });
                });
            });
        </script>
    @endpush
</div>
