<x-admin-layout title="Dashboard">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>

@php
    $statusColors = [
        'Novo'        => ['bg'=>'#dbeafe','color'=>'#1d4ed8'],
        'Em contato'  => ['bg'=>'#fef3c7','color'=>'#92400e'],
        'Qualificado' => ['bg'=>'#ede9fe','color'=>'#6d28d9'],
        'Convertido'  => ['bg'=>'#dcfce7','color'=>'#15803d'],
        'Perdido'     => ['bg'=>'#fee2e2','color'=>'#dc2626'],
    ];
    $prioColors = [
        'Crítica' => '#ef4444',
        'Alta'    => '#f59e0b',
        'Média'   => '#2563eb',
        'Baixa'   => '#94a3b8',
    ];
@endphp

{{-- Header --}}
<div style="margin-bottom:1.5rem;">
    <h1 style="font-size:1.25rem; font-weight:700; color:#1e3a5f; margin:0 0 2px;">Dashboard</h1>
    <p style="font-size:0.8125rem; color:#94a3b8; margin:0;">Visão geral atualizada em tempo real</p>
</div>

{{-- KPI Cards --}}
<div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(180px,1fr)); gap:1rem; margin-bottom:1.5rem;">

    {{-- Leads este mês --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem; display:flex; flex-direction:column; gap:0.5rem;">
        <div style="display:flex; align-items:center; justify-content:space-between;">
            <span style="font-size:0.75rem; font-weight:600; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Leads / mês</span>
            <div style="width:34px;height:34px;border-radius:9px;background:#eff6ff;display:flex;align-items:center;justify-content:center;">
                <svg width="16" height="16" fill="none" stroke="#2563eb" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
            </div>
        </div>
        <p style="font-size:2rem; font-weight:800; color:#1e3a5f; margin:0; line-height:1;">{{ $leadsNovosMes }}</p>
        <p style="font-size:0.75rem; color:#94a3b8; margin:0;">em {{ now()->translatedFormat('F') }}</p>
    </div>

    {{-- Demandas abertas --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem; display:flex; flex-direction:column; gap:0.5rem;">
        <div style="display:flex; align-items:center; justify-content:space-between;">
            <span style="font-size:0.75rem; font-weight:600; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Demandas abertas</span>
            <div style="width:34px;height:34px;border-radius:9px;background:#f0fdf4;display:flex;align-items:center;justify-content:center;">
                <svg width="16" height="16" fill="none" stroke="#25b87e" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7"/></svg>
            </div>
        </div>
        <p style="font-size:2rem; font-weight:800; color:#1e3a5f; margin:0; line-height:1;">{{ $demandasAbertas }}</p>
        <p style="font-size:0.75rem; color:#94a3b8; margin:0;">em andamento</p>
    </div>

    {{-- Vencidas --}}
    <div style="background:#fff; border:1px solid {{ $demandasVencidas > 0 ? '#fecaca' : '#e2e8f0' }}; border-radius:14px; padding:1.25rem; display:flex; flex-direction:column; gap:0.5rem; {{ $demandasVencidas > 0 ? 'background:#fff5f5;' : '' }}">
        <div style="display:flex; align-items:center; justify-content:space-between;">
            <span style="font-size:0.75rem; font-weight:600; color:{{ $demandasVencidas > 0 ? '#dc2626' : '#64748b' }}; text-transform:uppercase; letter-spacing:0.05em;">SLA vencido</span>
            <div style="width:34px;height:34px;border-radius:9px;background:#fee2e2;display:flex;align-items:center;justify-content:center;">
                <svg width="16" height="16" fill="none" stroke="#dc2626" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            </div>
        </div>
        <p style="font-size:2rem; font-weight:800; color:{{ $demandasVencidas > 0 ? '#dc2626' : '#1e3a5f' }}; margin:0; line-height:1;">{{ $demandasVencidas }}</p>
        <p style="font-size:0.75rem; color:#94a3b8; margin:0;">{{ $demandasHoje }} vencem hoje</p>
    </div>

    {{-- Contratos ativos --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem; display:flex; flex-direction:column; gap:0.5rem;">
        <div style="display:flex; align-items:center; justify-content:space-between;">
            <span style="font-size:0.75rem; font-weight:600; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Contratos ativos</span>
            <div style="width:34px;height:34px;border-radius:9px;background:#fef3c7;display:flex;align-items:center;justify-content:center;">
                <svg width="16" height="16" fill="none" stroke="#d97706" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
            </div>
        </div>
        <p style="font-size:2rem; font-weight:800; color:#1e3a5f; margin:0; line-height:1;">{{ $contratosAtivos }}</p>
        <p style="font-size:0.75rem; color:#94a3b8; margin:0;">em vigor</p>
    </div>

    {{-- Receita este mês --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem; display:flex; flex-direction:column; gap:0.5rem;">
        <div style="display:flex; align-items:center; justify-content:space-between;">
            <span style="font-size:0.75rem; font-weight:600; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Faturado / mês</span>
            <div style="width:34px;height:34px;border-radius:9px;background:#f0fdf4;display:flex;align-items:center;justify-content:center;">
                <svg width="16" height="16" fill="none" stroke="#25b87e" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            </div>
        </div>
        <p style="font-size:1.5rem; font-weight:800; color:#1e3a5f; margin:0; line-height:1;">R$ {{ number_format($receitaMes, 2, ',', '.') }}</p>
        <p style="font-size:0.75rem; color:#94a3b8; margin:0;">A receber: R$ {{ number_format($receitaAReceber, 2, ',', '.') }}</p>
    </div>

    {{-- Propostas pipeline --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem; display:flex; flex-direction:column; gap:0.5rem;">
        <div style="display:flex; align-items:center; justify-content:space-between;">
            <span style="font-size:0.75rem; font-weight:600; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;">Propostas pipeline</span>
            <div style="width:34px;height:34px;border-radius:9px;background:#f5f3ff;display:flex;align-items:center;justify-content:center;">
                <svg width="16" height="16" fill="none" stroke="#7c3aed" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
            </div>
        </div>
        <p style="font-size:2rem; font-weight:800; color:#1e3a5f; margin:0; line-height:1;">{{ $propostasAbertas }}</p>
        <p style="font-size:0.75rem; color:#94a3b8; margin:0;">{{ $propostasAceitasMes }} aceitas em {{ now()->translatedFormat('M') }}</p>
    </div>

    {{-- Cobranças em atraso --}}
    <div style="background:#fff; border:1px solid {{ $cobrancasVencidas > 0 ? '#fecaca' : '#e2e8f0' }}; border-radius:14px; padding:1.25rem; display:flex; flex-direction:column; gap:0.5rem; {{ $cobrancasVencidas > 0 ? 'background:#fff5f5;' : '' }}">
        <div style="display:flex; align-items:center; justify-content:space-between;">
            <span style="font-size:0.75rem; font-weight:600; color:{{ $cobrancasVencidas > 0 ? '#dc2626' : '#64748b' }}; text-transform:uppercase; letter-spacing:0.05em;">Em atraso</span>
            <div style="width:34px;height:34px;border-radius:9px;background:#fee2e2;display:flex;align-items:center;justify-content:center;">
                <svg width="16" height="16" fill="none" stroke="#dc2626" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
            </div>
        </div>
        <p style="font-size:2rem; font-weight:800; color:{{ $cobrancasVencidas > 0 ? '#dc2626' : '#1e3a5f' }}; margin:0; line-height:1;">{{ $cobrancasVencidas }}</p>
        <p style="font-size:0.75rem; color:#94a3b8; margin:0;">R$ {{ number_format($valorEmAtraso, 2, ',', '.') }} em atraso</p>
    </div>
</div>

{{-- Middle row: breakdowns --}}
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:1rem; margin-bottom:1.5rem;">

    {{-- Leads por status --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem;">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem;">
            <h2 style="font-size:0.8125rem; font-weight:700; color:#1e3a5f; margin:0;">Leads por status</h2>
            <a href="{{ route('leads.index') }}" style="font-size:0.75rem; color:#25b87e; text-decoration:none;">Ver todos →</a>
        </div>
        @php $totalLeads = $leadsPorStatus->sum(); @endphp
        <div style="display:flex; flex-direction:column; gap:0.625rem;">
            @foreach(\App\Models\Lead::statuses() as $status)
            @php
                $count = $leadsPorStatus[$status] ?? 0;
                $pct   = $totalLeads > 0 ? round($count / $totalLeads * 100) : 0;
                $sc    = $statusColors[$status] ?? ['bg'=>'#f1f5f9','color'=>'#64748b'];
            @endphp
            <div>
                <div style="display:flex; justify-content:space-between; margin-bottom:3px;">
                    <span style="font-size:0.75rem; font-weight:500; color:#1e3a5f;">{{ $status }}</span>
                    <span style="font-size:0.75rem; font-weight:700; color:{{ $sc['color'] }};">{{ $count }}</span>
                </div>
                <div style="height:6px; background:#f1f5f9; border-radius:100px; overflow:hidden;">
                    <div style="height:100%; width:{{ $pct }}%; background:{{ $sc['color'] }}; border-radius:100px; transition:width 0.6s;"></div>
                </div>
            </div>
            @endforeach
        </div>
    </div>

    {{-- Contratos por status --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem;">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem;">
            <h2 style="font-size:0.8125rem; font-weight:700; color:#1e3a5f; margin:0;">Contratos por status</h2>
            <a href="{{ route('contratos.index') }}" style="font-size:0.75rem; color:#25b87e; text-decoration:none;">Ver todos →</a>
        </div>
        @php
            $steps = \App\Models\Contrato::workflowSteps();
            $totalContratos = $contratosPorStatus->sum();
        @endphp
        <div style="display:flex; flex-direction:column; gap:0.5rem;">
            @foreach($steps as $key => $step)
            @php $count = $contratosPorStatus[$key] ?? 0; if(!$count) continue; @endphp
            <div style="display:flex; align-items:center; justify-content:space-between; padding:0.375rem 0.5rem; border-radius:8px; background:#f8fafc;">
                <div style="display:flex; align-items:center; gap:0.5rem;">
                    <span style="width:8px; height:8px; border-radius:50%; background:{{ $step['color'] }}; flex-shrink:0;"></span>
                    <span style="font-size:0.75rem; color:#374151;">{{ $step['label'] }}</span>
                </div>
                <span style="font-size:0.75rem; font-weight:700; color:{{ $step['color'] }};">{{ $count }}</span>
            </div>
            @endforeach
            @if($totalContratos === 0)
                <p style="font-size:0.8125rem; color:#94a3b8; text-align:center; padding:1rem 0;">Nenhum contrato ainda</p>
            @endif
        </div>
    </div>
</div>

{{-- Charts row --}}
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:1rem; margin-bottom:1.5rem;">

    {{-- Leads 6 meses --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem;">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem;">
            <h2 style="font-size:0.8125rem; font-weight:700; color:#1e3a5f; margin:0;">Leads — últimos 6 meses</h2>
        </div>
        <canvas id="leadsChart" height="110"></canvas>
    </div>

    {{-- Demandas por setor --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem;">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem;">
            <h2 style="font-size:0.8125rem; font-weight:700; color:#1e3a5f; margin:0;">Demandas por setor</h2>
        </div>
        <canvas id="setorChart" height="130"></canvas>
    </div>
</div>

{{-- Receita chart row --}}
<div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:1.25rem; margin-bottom:1.5rem;">
    <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem;">
        <h2 style="font-size:0.8125rem; font-weight:700; color:#1e3a5f; margin:0;">Receita recebida — últimos 6 meses</h2>
        <a href="{{ route('admin.financeiro.index') }}" style="font-size:0.75rem; color:#25b87e; text-decoration:none;">Ver financeiro →</a>
    </div>
    <canvas id="receitaChart" height="80"></canvas>
</div>

{{-- Bottom row: recent activity --}}
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:1rem;">

    {{-- Últimos leads --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; overflow:hidden;">
        <div style="padding:1rem 1.25rem; border-bottom:1px solid #f1f5f9; display:flex; align-items:center; justify-content:space-between;">
            <h2 style="font-size:0.8125rem; font-weight:700; color:#1e3a5f; margin:0;">Últimos leads</h2>
            <a href="{{ route('leads.index') }}" style="font-size:0.75rem; color:#25b87e; text-decoration:none;">Ver CRM →</a>
        </div>
        <div>
            @forelse($leadsRecentes as $lead)
            @php $sc = $statusColors[$lead->status] ?? ['bg'=>'#f1f5f9','color'=>'#64748b']; @endphp
            <div style="padding:0.75rem 1.25rem; border-bottom:1px solid #f8fafc; display:flex; align-items:center; gap:0.75rem;">
                <div style="width:32px;height:32px;border-radius:9px;background:#e8f8f1;display:flex;align-items:center;justify-content:center;font-size:0.75rem;font-weight:700;color:#25b87e;flex-shrink:0;">
                    {{ strtoupper(substr($lead->name, 0, 2)) }}
                </div>
                <div style="flex:1; min-width:0;">
                    <p style="font-size:0.8125rem; font-weight:600; color:#1e3a5f; margin:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">{{ $lead->name }}</p>
                    <p style="font-size:0.6875rem; color:#94a3b8; margin:0;">{{ $lead->company ?? $lead->email }}</p>
                </div>
                <span style="padding:0.2rem 0.5rem; border-radius:100px; font-size:0.6875rem; font-weight:600; background:{{ $sc['bg'] }}; color:{{ $sc['color'] }}; white-space:nowrap; flex-shrink:0;">
                    {{ $lead->status }}
                </span>
            </div>
            @empty
            <p style="padding:1.5rem; text-align:center; color:#94a3b8; font-size:0.8125rem;">Nenhum lead ainda</p>
            @endforelse
        </div>
    </div>

    {{-- Demandas urgentes --}}
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:14px; overflow:hidden;">
        <div style="padding:1rem 1.25rem; border-bottom:1px solid #f1f5f9; display:flex; align-items:center; justify-content:space-between;">
            <h2 style="font-size:0.8125rem; font-weight:700; color:#1e3a5f; margin:0;">Demandas prioritárias</h2>
            <a href="{{ route('kanban.index') }}" style="font-size:0.75rem; color:#25b87e; text-decoration:none;">Ver Kanban →</a>
        </div>
        <div>
            @forelse($demandasUrgentes as $dem)
            @php $vencida = $dem->isVencida(); $hoje = $dem->isVenceHoje(); @endphp
            <div style="padding:0.75rem 1.25rem; border-bottom:1px solid #f8fafc; display:flex; align-items:center; gap:0.75rem;">
                <span style="width:8px;height:8px;border-radius:50%;flex-shrink:0;background:{{ $prioColors[$dem->prioridade] ?? '#94a3b8' }};"></span>
                <div style="flex:1; min-width:0;">
                    <p style="font-size:0.8125rem; font-weight:600; color:#1e3a5f; margin:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">{{ $dem->titulo }}</p>
                    <p style="font-size:0.6875rem; color:#94a3b8; margin:0;">{{ $dem->cliente }} · {{ $dem->setor }}</p>
                </div>
                @if($vencida)
                    <span style="padding:0.2rem 0.5rem; border-radius:100px; font-size:0.6875rem; font-weight:700; background:#fee2e2; color:#dc2626; white-space:nowrap; flex-shrink:0;">Vencida</span>
                @elseif($hoje)
                    <span style="padding:0.2rem 0.5rem; border-radius:100px; font-size:0.6875rem; font-weight:700; background:#fef3c7; color:#92400e; white-space:nowrap; flex-shrink:0;">Hoje</span>
                @elseif($dem->sla_vencimento)
                    <span style="padding:0.2rem 0.5rem; border-radius:100px; font-size:0.6875rem; color:#64748b; background:#f1f5f9; white-space:nowrap; flex-shrink:0;">{{ $dem->sla_vencimento->format('d/m') }}</span>
                @endif
            </div>
            @empty
            <p style="padding:1.5rem; text-align:center; color:#94a3b8; font-size:0.8125rem;">Nenhuma demanda aberta</p>
            @endforelse
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const font = { family: 'Poppins, sans-serif', size: 11 };
    const gridColor = '#f1f5f9';
    const navy = '#1e3a5f';
    const green = '#25b87e';

    // Leads chart
    new Chart(document.getElementById('leadsChart'), {
        type: 'bar',
        data: {
            labels: @json($leadsChartLabels),
            datasets: [{
                label: 'Leads',
                data: @json($leadsChartData),
                backgroundColor: 'rgba(37,184,126,0.18)',
                borderColor: green,
                borderWidth: 2,
                borderRadius: 6,
            }]
        },
        options: {
            responsive: true, maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: {
                x: { grid: { display: false }, ticks: { font, color: '#94a3b8' } },
                y: { grid: { color: gridColor }, ticks: { font, color: '#94a3b8', stepSize: 1 }, beginAtZero: true },
            }
        }
    });

    // Setor doughnut
    const setorLabels = @json($demandaPorSetor->keys());
    const setorData   = @json($demandaPorSetor->values());
    const palette = ['#1e3a5f','#25b87e','#2563eb','#d97706','#7c3aed','#0369a1','#dc2626','#475569'];
    new Chart(document.getElementById('setorChart'), {
        type: 'doughnut',
        data: {
            labels: setorLabels,
            datasets: [{ data: setorData, backgroundColor: palette, borderWidth: 0, hoverOffset: 4 }]
        },
        options: {
            responsive: true, maintainAspectRatio: true, cutout: '65%',
            plugins: {
                legend: { position: 'bottom', labels: { font, color: navy, boxWidth: 10, padding: 12 } }
            }
        }
    });

    // Receita chart
    new Chart(document.getElementById('receitaChart'), {
        type: 'line',
        data: {
            labels: @json($receitaChartLabels),
            datasets: [{
                label: 'Receita (R$)',
                data: @json($receitaChartData),
                borderColor: navy,
                backgroundColor: 'rgba(30,58,95,0.07)',
                borderWidth: 2,
                pointBackgroundColor: navy,
                pointRadius: 4,
                fill: true,
                tension: 0.35,
            }]
        },
        options: {
            responsive: true, maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: {
                x: { grid: { display: false }, ticks: { font, color: '#94a3b8' } },
                y: {
                    grid: { color: gridColor }, beginAtZero: true,
                    ticks: { font, color: '#94a3b8', callback: v => 'R$ ' + v.toLocaleString('pt-BR') }
                },
            }
        }
    });
});
</script>

</x-admin-layout>
