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

<x-layouts.app title="Visão geral" subtitle="Todas as empresas da plataforma">
    <x-slot:actions>
        <a href="{{ route('master.empresas.create') }}" class="btn-primary btn-sm">Nova empresa</a>
    </x-slot:actions>

    <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <x-stat label="Empresas" :value="number_format($empresas, 0, ',', '.')"
                :hint="number_format($empresasAtivas, 0, ',', '.').' ativas'" tone="brand" />
        <x-stat label="Monitores ativos" :value="number_format($monitorAtivo, 0, ',', '.')"
                hint="com certificado instalado" tone="emerald" />
        <x-stat label="XMLs arquivados" :value="number_format($notas, 0, ',', '.')"
                :hint="number_format($notasMes, 0, ',', '.').' neste mês'" />
        <x-stat label="Valor movimentado" :value="Number::currency((float) $valorTotal, 'BRL', 'pt_BR')"
                :hint="number_format($usuarios, 0, ',', '.').' usuários'" />
    </div>

    @php $maximo = max(1, collect($serie)->max('total')); @endphp
    <div class="card card-pad mt-6">
        <div class="flex items-baseline justify-between">
            <h2 class="text-sm font-semibold text-slate-900">XMLs recebidos por mês (plataforma)</h2>
            <span class="text-xs text-slate-500">últimos 12 meses</span>
        </div>

        <div class="mt-6 flex h-40 items-end gap-2 sm:gap-3">
            @foreach ($serie as $ponto)
                <div class="group flex flex-1 flex-col items-center justify-end gap-2">
                    <span class="tabular text-[11px] font-medium text-slate-500 opacity-0 transition group-hover:opacity-100">{{ $ponto['total'] }}</span>
                    <div class="w-full rounded-t bg-brand-600/85 transition group-hover:bg-brand-700"
                         style="height: {{ max(3, (int) round($ponto['total'] / $maximo * 100)) }}%"
                         title="{{ $ponto['label'] }}: {{ $ponto['total'] }}"></div>
                    <span class="text-[11px] text-slate-400">{{ $ponto['label'] }}</span>
                </div>
            @endforeach
        </div>
    </div>

    <div class="mt-6 grid gap-6 lg:grid-cols-3">
        {{-- Falhas --}}
        <div class="card lg:col-span-2">
            <div class="flex items-center justify-between border-b border-slate-100 px-5 py-4">
                <h2 class="text-sm font-semibold text-slate-900">Falhas recentes do monitor</h2>
                <a href="{{ route('master.logs') }}" class="text-xs font-semibold text-brand-700 hover:text-brand-800">Ver todos os logs</a>
            </div>

            @forelse ($ultimosErros as $log)
                <div class="flex items-start justify-between gap-4 border-b border-slate-50 px-5 py-3 last:border-0">
                    <div class="min-w-0">
                        <a href="{{ route('master.empresas.show', $log->company_id) }}"
                           class="text-sm font-medium text-brand-700 hover:text-brand-800">
                            {{ $log->company?->razao_social }}
                        </a>
                        <p class="mt-0.5 truncate text-xs text-slate-500">{{ $log->mensagem }}</p>
                    </div>
                    <p class="shrink-0 text-xs text-slate-400">{{ $log->created_at->diffForHumans() }}</p>
                </div>
            @empty
                <p class="px-5 py-10 text-center text-sm text-slate-500">Nenhuma falha registrada. Tudo em ordem.</p>
            @endforelse
        </div>

        <div class="space-y-6">
            {{-- Documentos não interpretados --}}
            @if ($pendentes->isNotEmpty())
                <div class="card overflow-hidden border-amber-300">
                    <div class="border-b border-amber-200 bg-amber-50 px-5 py-4">
                        <h2 class="text-sm font-semibold text-amber-900">
                            {{ number_format($totalPendentes, 0, ',', '.') }} documento(s) não interpretado(s)
                        </h2>
                        <p class="mt-1 text-xs text-amber-800">Arquivados em bruto — nada foi perdido.</p>
                    </div>
                    @foreach ($pendentes as $pendente)
                        <div class="flex items-center justify-between gap-3 border-b border-slate-50 px-5 py-3 last:border-0">
                            <div class="min-w-0">
                                <a href="{{ route('master.empresas.show', $pendente->company_id) }}"
                                   class="truncate text-sm text-brand-700 hover:text-brand-800">
                                    {{ Str::limit($pendente->company?->razao_social, 24) }}
                                </a>
                                <p class="text-xs text-slate-500">{{ $pendente->raiz ?: $pendente->schema_dfe ?: 'formato desconhecido' }}</p>
                            </div>
                            <span class="tabular shrink-0 text-xs text-slate-500">NSU {{ $pendente->nsu }}</span>
                        </div>
                    @endforeach
                </div>
            @endif

            {{-- Certificados a vencer --}}
            <div class="card">
                <div class="border-b border-slate-100 px-5 py-4">
                    <h2 class="text-sm font-semibold text-slate-900">Certificados vencendo em 30 dias</h2>
                </div>
                @forelse ($certificadosVencendo as $empresa)
                    <a href="{{ route('master.empresas.show', $empresa) }}"
                       class="flex items-center justify-between gap-3 border-b border-slate-50 px-5 py-3 transition last:border-0 hover:bg-slate-50">
                        <span class="min-w-0 truncate text-sm text-slate-800">{{ $empresa->razao_social }}</span>
                        <span class="tabular shrink-0 text-xs font-medium text-amber-700">
                            {{ $empresa->cert_valid_to->format('d/m/Y') }}
                        </span>
                    </a>
                @empty
                    <p class="px-5 py-8 text-center text-sm text-slate-500">Nenhum certificado próximo do vencimento.</p>
                @endforelse
            </div>

            {{-- Ranking --}}
            <div class="card">
                <div class="border-b border-slate-100 px-5 py-4">
                    <h2 class="text-sm font-semibold text-slate-900">Empresas por volume</h2>
                </div>
                @forelse ($topEmpresas as $empresa)
                    <a href="{{ route('master.empresas.show', $empresa) }}"
                       class="flex items-center justify-between gap-3 border-b border-slate-50 px-5 py-3 transition last:border-0 hover:bg-slate-50">
                        <span class="min-w-0 truncate text-sm text-slate-800">{{ $empresa->razao_social }}</span>
                        <span class="tabular shrink-0 text-xs text-slate-500">{{ number_format($empresa->notas_fiscais_count, 0, ',', '.') }}</span>
                    </a>
                @empty
                    <p class="px-5 py-8 text-center text-sm text-slate-500">Nenhuma empresa cadastrada.</p>
                @endforelse
            </div>
        </div>
    </div>
</x-layouts.app>
