@use('Illuminate\Support\Number')
@use('Illuminate\Support\Str')

<div class="space-y-4">

    {{-- Filtros --}}
    <div class="card card-pad">
        <div class="grid gap-4 lg:grid-cols-12">
            <div class="lg:col-span-4">
                <label class="label" for="f-busca">Buscar</label>
                <input id="f-busca" type="search" wire:model.live.debounce.400ms="busca" class="input"
                       placeholder="Fornecedor, CNPJ, nº da nota ou chave">
            </div>

            <div class="lg:col-span-2">
                <label class="label" for="f-de">Emissão de</label>
                <input id="f-de" type="date" wire:model.live="de" class="input tabular">
            </div>

            <div class="lg:col-span-2">
                <label class="label" for="f-ate">até</label>
                <input id="f-ate" type="date" wire:model.live="ate" class="input tabular">
            </div>

            <div class="lg:col-span-2">
                <label class="label" for="f-situacao">Situação</label>
                <select id="f-situacao" wire:model.live="situacao" class="input">
                    <option value="">Todas</option>
                    <option value="autorizada">Autorizada</option>
                    <option value="cancelada">Cancelada</option>
                    <option value="denegada">Denegada</option>
                </select>
            </div>

            <div class="lg:col-span-2">
                <label class="label" for="f-tipo">Arquivo</label>
                <select id="f-tipo" wire:model.live="tipo" class="input">
                    <option value="">Todos</option>
                    <option value="completo">XML completo</option>
                    <option value="resumo">Somente resumo</option>
                </select>
            </div>
        </div>

        <div class="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-slate-100 pt-4">
            <div class="tabular text-sm text-slate-600">
                <strong class="text-slate-900">{{ number_format($resumo['total'], 0, ',', '.') }}</strong> nota(s)
                · {{ Number::currency($resumo['valor'], 'BRL', 'pt_BR') }}
                · {{ number_format($resumo['completas'], 0, ',', '.') }} com XML
            </div>

            <div class="flex flex-wrap items-center gap-2">
                <select wire:model.live="manifestacao" class="input w-auto py-1.5 text-xs">
                    <option value="">Manifestação: todas</option>
                    <option value="pendente">Sem manifestação</option>
                    <option value="ciencia">Ciência</option>
                    <option value="confirmada">Confirmada</option>
                    <option value="desconhecida">Desconhecimento</option>
                    <option value="nao_realizada">Não realizada</option>
                </select>

                <button type="button" wire:click="limpar" class="btn-secondary btn-sm">Limpar filtros</button>

                @unless ($global)
                    <div x-data="{ opcoes: false }" class="relative">
                        <div class="flex">
                            <a class="btn-primary btn-sm rounded-r-none"
                               href="{{ route('painel.download.lote', array_merge($this->filtros, ['ids' => array_map('intval', $selecionadas)])) }}">
                                <svg class="size-4" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"/>
                                </svg>
                                {{ $selecionadas ? 'Baixar '.count($selecionadas).' selecionada(s)' : 'Baixar .zip do filtro' }}
                            </a>
                            <button type="button" @click="opcoes = !opcoes" title="Opções do pacote"
                                    class="btn-primary btn-sm rounded-l-none border-l border-white/20 px-2">
                                <svg class="size-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5"/>
                                </svg>
                            </button>
                        </div>

                        <div x-show="opcoes" x-cloak @click.outside="opcoes = false"
                             class="absolute right-0 z-20 mt-2 w-80 rounded-lg border border-slate-200 bg-white p-4 text-left shadow-lg">
                            <p class="text-xs font-semibold tracking-wide text-slate-500 uppercase">Organização do pacote</p>

                            <div class="mt-3 space-y-2">
                                <label class="flex cursor-pointer items-start gap-2 text-sm text-slate-700">
                                    <input type="radio" value="emissao" wire:model.live="agrupar"
                                           class="mt-0.5 size-4 cursor-pointer border-slate-300 text-brand-700 focus:ring-brand-500">
                                    <span>
                                        <span class="block font-medium">Por data de emissão</span>
                                        <span class="block text-xs text-slate-500">Competência da nota. Padrão.</span>
                                    </span>
                                </label>

                                <label class="flex cursor-pointer items-start gap-2 text-sm text-slate-700">
                                    <input type="radio" value="recebimento" wire:model.live="agrupar"
                                           class="mt-0.5 size-4 cursor-pointer border-slate-300 text-brand-700 focus:ring-brand-500">
                                    <span>
                                        <span class="block font-medium">Por data de recebimento</span>
                                        <span class="block text-xs text-slate-500">Para quem escritura pela entrada.</span>
                                    </span>
                                </label>
                            </div>

                            <label class="mt-3 flex cursor-pointer items-start gap-2 border-t border-slate-100 pt-3 text-sm text-slate-700">
                                <input type="checkbox" wire:model.live="incluirEventos"
                                       class="mt-0.5 size-4 cursor-pointer rounded border-slate-300 text-brand-700 focus:ring-brand-500">
                                <span>
                                    <span class="block font-medium">Incluir eventos</span>
                                    <span class="block text-xs text-slate-500">Cartas de correção e cancelamentos, em EVENTOS/.</span>
                                </span>
                            </label>

                            <p class="mt-3 rounded-lg bg-slate-50 px-3 py-2 text-xs leading-relaxed text-slate-500">
                                Canceladas e denegadas saem em pastas próprias, fora das competências.
                                O pacote inclui <strong>relacao.csv</strong> para conferência.
                            </p>
                        </div>
                    </div>
                @endunless
            </div>
        </div>
    </div>

    {{-- Tabela --}}
    <div class="card overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-slate-200">
                <thead class="bg-slate-50">
                    <tr>
                        @unless ($global)
                            <th class="w-10 px-4 py-3">
                                <input type="checkbox" wire:model.live="selecionarTodas" aria-label="Selecionar todas"
                                       class="size-4 cursor-pointer rounded border-slate-300 text-brand-700 focus:ring-brand-500">
                            </th>
                        @endunless

                        @if ($global)
                            <th class="th">Empresa</th>
                        @endif

                        <th class="th">
                            <button type="button" wire:click="ordenar('emit_nome')" class="flex cursor-pointer items-center gap-1 hover:text-slate-700">
                                Fornecedor
                                @if ($ordenarPor === 'emit_nome') <span class="text-brand-600">{{ $direcao === 'asc' ? '↑' : '↓' }}</span> @endif
                            </button>
                        </th>
                        <th class="th">
                            <button type="button" wire:click="ordenar('numero')" class="flex cursor-pointer items-center gap-1 hover:text-slate-700">
                                Nota
                                @if ($ordenarPor === 'numero') <span class="text-brand-600">{{ $direcao === 'asc' ? '↑' : '↓' }}</span> @endif
                            </button>
                        </th>
                        <th class="th">
                            <button type="button" wire:click="ordenar('data_emissao')" class="flex cursor-pointer items-center gap-1 hover:text-slate-700">
                                Emissão
                                @if ($ordenarPor === 'data_emissao') <span class="text-brand-600">{{ $direcao === 'asc' ? '↑' : '↓' }}</span> @endif
                            </button>
                        </th>
                        <th class="th text-right">
                            <button type="button" wire:click="ordenar('valor_total')" class="ml-auto flex cursor-pointer items-center gap-1 hover:text-slate-700">
                                Valor
                                @if ($ordenarPor === 'valor_total') <span class="text-brand-600">{{ $direcao === 'asc' ? '↑' : '↓' }}</span> @endif
                            </button>
                        </th>
                        <th class="th">Situação</th>
                        <th class="th">XML</th>
                        <th class="th sr-only">Ações</th>
                    </tr>
                </thead>

                <tbody class="divide-y divide-slate-100 bg-white">
                    @forelse ($notas as $nota)
                        <tr wire:key="nota-{{ $nota->id }}" class="transition hover:bg-slate-50">
                            @unless ($global)
                                <td class="px-4 py-3">
                                    <input type="checkbox" value="{{ $nota->id }}" wire:model.live="selecionadas"
                                           aria-label="Selecionar nota {{ $nota->numero }}"
                                           class="size-4 cursor-pointer rounded border-slate-300 text-brand-700 focus:ring-brand-500">
                                </td>
                            @endunless

                            @if ($global)
                                <td class="td">
                                    <a href="{{ route('master.empresas.show', $nota->company_id) }}" class="font-medium text-brand-700 hover:text-brand-800">
                                        {{ Str::limit($nota->company?->razao_social, 28) }}
                                    </a>
                                </td>
                            @endif

                            <td class="td">
                                <p class="font-medium text-slate-900">{{ Str::limit($nota->emit_nome ?: '—', 34) }}</p>
                                <p class="tabular text-xs text-slate-500">{{ $nota->emit_cnpj_formatado }}</p>
                            </td>

                            <td class="td tabular">
                                {{ $nota->numero }}<span class="text-slate-400">/{{ $nota->serie }}</span>
                            </td>

                            <td class="td tabular">{{ $nota->data_emissao?->format('d/m/Y') ?: '—' }}</td>

                            <td class="td tabular text-right font-medium text-slate-900">
                                {{ Number::currency((float) $nota->valor_total, 'BRL', 'pt_BR') }}
                            </td>

                            <td class="td"><x-situacao-badge :situacao="$nota->situacao" /></td>

                            <td class="td">
                                @if ($nota->tem_xml_completo)
                                    <span class="badge bg-brand-50 text-brand-700 ring-1 ring-brand-200">Completo</span>
                                @else
                                    <span class="badge bg-slate-100 text-slate-600" title="Manifeste ciência da operação para liberar o XML completo">Resumo</span>
                                @endif
                            </td>

                            <td class="td text-right whitespace-nowrap">
                                @if ($nota->tem_xml_completo && ! $global)
                                    <a href="{{ route('painel.notas.download', $nota) }}" title="Baixar XML"
                                       class="inline-flex rounded-md p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-brand-700">
                                        <svg class="size-4" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"/>
                                        </svg>
                                    </a>
                                    <a href="{{ route('painel.notas.danfe', $nota) }}" target="_blank" rel="noopener" title="Imprimir DANFE"
                                       class="inline-flex rounded-md p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-brand-700">
                                        <svg class="size-4" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0 1 10.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0 .229 2.523a1.125 1.125 0 0 1-1.12 1.227H7.231c-.662 0-1.18-.568-1.12-1.227L6.34 18m11.318 0h1.091A2.25 2.25 0 0 0 21 15.75V9.456c0-1.081-.768-2.015-1.837-2.175a48.055 48.055 0 0 0-1.913-.247M6.34 18H5.25A2.25 2.25 0 0 1 3 15.75V9.456c0-1.081.768-2.015 1.837-2.175a48.041 48.041 0 0 1 1.913-.247m10.5 0a48.536 48.536 0 0 0-10.5 0m10.5 0V3.375c0-.621-.504-1.125-1.125-1.125h-8.25c-.621 0-1.125.504-1.125 1.125v3.659"/>
                                        </svg>
                                    </a>
                                @endif
                                @if ($global && $nota->tem_xml_completo)
                                    <a href="{{ route('master.notas.download', $nota) }}" title="Baixar XML"
                                       class="inline-flex rounded-md p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-brand-700">
                                        <svg class="size-4" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"/>
                                        </svg>
                                    </a>
                                    <a href="{{ route('master.notas.danfe', $nota) }}" target="_blank" rel="noopener" title="Imprimir DANFE"
                                       class="inline-flex rounded-md p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-brand-700">
                                        <svg class="size-4" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0 1 10.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0 .229 2.523a1.125 1.125 0 0 1-1.12 1.227H7.231c-.662 0-1.18-.568-1.12-1.227L6.34 18m11.318 0h1.091A2.25 2.25 0 0 0 21 15.75V9.456c0-1.081-.768-2.015-1.837-2.175a48.055 48.055 0 0 0-1.913-.247M6.34 18H5.25A2.25 2.25 0 0 1 3 15.75V9.456c0-1.081.768-2.015 1.837-2.175a48.041 48.041 0 0 1 1.913-.247m10.5 0a48.536 48.536 0 0 0-10.5 0m10.5 0V3.375c0-.621-.504-1.125-1.125-1.125h-8.25c-.621 0-1.125.504-1.125 1.125v3.659"/>
                                        </svg>
                                    </a>
                                @endif

                                <a href="{{ route($global ? 'master.notas.show' : 'painel.notas.show', $nota) }}"
                                   class="inline-flex rounded-md p-1.5 text-slate-500 transition hover:bg-slate-100 hover:text-brand-700" title="Detalhes">
                                    <svg class="size-4" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5"/>
                                    </svg>
                                </a>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="9" class="px-4 py-16 text-center">
                                <p class="text-sm font-medium text-slate-700">Nenhuma nota encontrada</p>
                                <p class="mt-1 text-sm text-slate-500">Ajuste os filtros ou aguarde o próximo ciclo do monitor.</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        @if ($notas->hasPages())
            <div class="border-t border-slate-100 px-4 py-3">
                {{ $notas->onEachSide(1)->links() }}
            </div>
        @endif
    </div>
</div>
