@use('Illuminate\Support\Number')

<x-layouts.app title="Painel" :subtitle="$company?->razao_social">
    <x-slot:actions>
        <form method="POST" action="{{ route('painel.monitor.sincronizar') }}">
            @csrf
            <button class="btn-primary btn-sm">
                <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="M16.023 9.348h4.992V4.356m-.001 0-3.181 3.183a8.25 8.25 0 0 0-13.803 3.7M4.031 9.865v4.992m0 0h4.99m-4.99 0 3.181-3.183a8.25 8.25 0 0 0 13.803-3.7"/>
                </svg>
                Sincronizar agora
            </button>
        </form>
    </x-slot:actions>

    {{-- Avisos de configuração --}}
    @if (! $company?->hasCertificate())
        <div class="mb-6 flex flex-wrap items-center justify-between gap-4 rounded-lg border border-amber-200 bg-amber-50 px-5 py-4">
            <div>
                <p class="text-sm font-semibold text-amber-900">O monitor ainda não está ativo</p>
                <p class="mt-0.5 text-sm text-amber-800">Envie o certificado digital A1 para que possamos consultar a SEFAZ em nome da empresa.</p>
            </div>
            <a href="{{ route('painel.certificado') }}" class="btn-primary btn-sm">Enviar certificado</a>
        </div>
    @elseif ($company->certificateExpired())
        <div class="mb-6 flex flex-wrap items-center justify-between gap-4 rounded-lg border border-rose-200 bg-rose-50 px-5 py-4">
            <div>
                <p class="text-sm font-semibold text-rose-900">Certificado digital vencido</p>
                <p class="mt-0.5 text-sm text-rose-800">Venceu em {{ $company->cert_valid_to->format('d/m/Y') }}. O monitor está parado até a substituição.</p>
            </div>
            <a href="{{ route('painel.certificado') }}" class="btn-primary btn-sm">Substituir</a>
        </div>
    @elseif ($company->certificateExpiringSoon())
        <div class="mb-6 rounded-lg border border-amber-200 bg-amber-50 px-5 py-4 text-sm text-amber-800">
            Seu certificado vence em <strong>{{ $company->cert_valid_to->format('d/m/Y') }}</strong>. Programe a renovação para o monitor não parar.
        </div>
    @endif

    {{-- Indicadores --}}
    <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <x-stat label="Notas arquivadas" :value="number_format($totais->total, 0, ',', '.')"
                :hint="number_format($totais->completas ?? 0, 0, ',', '.').' com XML completo'" tone="brand" />
        <x-stat label="Valor total" :value="Number::currency((float) $totais->valor, 'BRL', 'pt_BR')" />
        <x-stat label="Notas no mês" :value="number_format($mes->total, 0, ',', '.')"
                :hint="Number::currency((float) $mes->valor, 'BRL', 'pt_BR')" />
        <x-stat label="Canceladas" :value="number_format($totais->canceladas ?? 0, 0, ',', '.')"
                hint="Situação atualizada pelos eventos" tone="rose" />
    </div>

    {{-- Volume mensal --}}
    @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">Notas recebidas por mês</h2>
            <span class="text-xs text-slate-500">últimos 12 meses</span>
        </div>

        <div class="mt-6 flex h-44 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'] }} nota(s)"></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">
        {{-- Últimas notas --}}
        <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">Últimas notas recebidas</h2>
                <a href="{{ route('painel.notas') }}" class="text-xs font-semibold text-brand-700 hover:text-brand-800">Ver todas</a>
            </div>

            @forelse ($ultimasNotas as $nota)
                <a href="{{ route('painel.notas.show', $nota) }}"
                   class="flex items-center justify-between gap-4 border-b border-slate-50 px-5 py-3 transition last:border-0 hover:bg-slate-50">
                    <div class="min-w-0">
                        <p class="truncate text-sm font-medium text-slate-800">{{ $nota->emit_nome ?: 'Emitente não informado' }}</p>
                        <p class="tabular text-xs text-slate-500">
                            {{ $nota->emit_cnpj_formatado }} · NF {{ $nota->numero }}/{{ $nota->serie }}
                        </p>
                    </div>
                    <div class="shrink-0 text-right">
                        <p class="tabular text-sm font-semibold text-slate-900">{{ Number::currency((float) $nota->valor_total, 'BRL', 'pt_BR') }}</p>
                        <p class="text-xs text-slate-500">{{ $nota->data_emissao?->format('d/m/Y') }}</p>
                    </div>
                </a>
            @empty
                <p class="px-5 py-10 text-center text-sm text-slate-500">
                    Nenhuma nota arquivada ainda. Assim que o monitor rodar, elas aparecem aqui.
                </p>
            @endforelse
        </div>

        <div class="space-y-6">
            {{-- Fornecedores --}}
            <div class="card">
                <div class="border-b border-slate-100 px-5 py-4">
                    <h2 class="text-sm font-semibold text-slate-900">Maiores fornecedores</h2>
                </div>
                @forelse ($topFornecedores as $f)
                    <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">
                            <p class="truncate text-sm text-slate-800">{{ $f->emit_nome }}</p>
                            <p class="tabular text-xs text-slate-500">{{ $f->notas }} nota(s)</p>
                        </div>
                        <p class="tabular shrink-0 text-sm font-medium text-slate-900">
                            {{ Number::currency((float) $f->valor, 'BRL', 'pt_BR') }}
                        </p>
                    </div>
                @empty
                    <p class="px-5 py-8 text-center text-sm text-slate-500">Sem dados ainda.</p>
                @endforelse
            </div>

            {{-- Monitor --}}
            <div class="card">
                <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">Sincronizações</h2>
                    <a href="{{ route('painel.monitor') }}" class="text-xs font-semibold text-brand-700 hover:text-brand-800">Configurar</a>
                </div>
                @forelse ($ultimasSyncs as $log)
                    <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">
                            <p class="text-sm text-slate-800">{{ $log->statusLabel() }}</p>
                            <p class="text-xs text-slate-500">{{ $log->created_at->diffForHumans() }}</p>
                        </div>
                        <span class="tabular shrink-0 text-xs text-slate-500">
                            +{{ $log->docs_novos }} nota(s)
                        </span>
                    </div>
                @empty
                    <p class="px-5 py-8 text-center text-sm text-slate-500">O monitor ainda não rodou.</p>
                @endforelse
            </div>
        </div>
    </div>
</x-layouts.app>
