<x-admin-layout title="CRM de Leads">

    {{-- Stats --}}
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 1rem; margin-bottom: 1.75rem;">
        @php
            $cards = [
                ['label' => 'Total de leads',  'value' => $stats['total'],       'color' => '#1e3a5f'],
                ['label' => 'Novos',           'value' => $stats['novos'],       'color' => '#3b82f6'],
                ['label' => 'Em contato',      'value' => $stats['em_contato'],  'color' => '#f59e0b'],
                ['label' => 'Convertidos',     'value' => $stats['convertidos'], 'color' => '#25b87e'],
            ];
        @endphp
        @foreach($cards as $card)
            <div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 14px; padding: 1.25rem 1.5rem;">
                <p style="font-size: 0.75rem; font-weight: 600; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 0.5rem;">{{ $card['label'] }}</p>
                <p style="font-size: 2rem; font-weight: 800; color: {{ $card['color'] }}; margin: 0;">{{ $card['value'] }}</p>
            </div>
        @endforeach
    </div>

    {{-- Filter + header --}}
    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; flex-wrap: wrap; gap: 0.75rem;">
        <h2 style="font-size: 1rem; font-weight: 700; color: #1e3a5f; margin: 0;">
            Leads recebidos
            @if($filtro)
                <span style="font-size: 0.8125rem; font-weight: 500; color: #94a3b8;">— {{ $filtro }}</span>
            @endif
        </h2>
        <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
            <a href="{{ route('leads.index') }}"
               style="padding: 0.4375rem 0.875rem; border-radius: 8px; font-size: 0.8125rem; font-weight: 500; text-decoration: none; border: 1.5px solid {{ !$filtro ? '#25b87e' : '#e2e8f0' }}; color: {{ !$filtro ? '#25b87e' : '#64748b' }}; background: {{ !$filtro ? 'rgba(37,184,126,0.07)' : '#fff' }};">
                Todos
            </a>
            @foreach($statuses as $s)
                <a href="{{ route('leads.index', ['status' => $s]) }}"
                   style="padding: 0.4375rem 0.875rem; border-radius: 8px; font-size: 0.8125rem; font-weight: 500; text-decoration: none; border: 1.5px solid {{ $filtro === $s ? '#25b87e' : '#e2e8f0' }}; color: {{ $filtro === $s ? '#25b87e' : '#64748b' }}; background: {{ $filtro === $s ? 'rgba(37,184,126,0.07)' : '#fff' }};">
                    {{ $s }}
                </a>
            @endforeach
        </div>
    </div>

    {{-- Lead cards --}}
    <div style="display: flex; flex-direction: column; gap: 0.75rem;">
        @if($leads->isEmpty())
            <div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 16px; text-align: center; padding: 4rem 2rem;">
                <svg style="width: 40px; height: 40px; color: #cbd5e1; margin: 0 auto 1rem; display: block;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" 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>
                <p style="color: #94a3b8; font-size: 0.9rem;">Nenhum lead encontrado.</p>
            </div>
        @else
            @foreach($leads as $lead)
                @php
                    $perfil = $lead->perfil_simulador ?? [];
                    $isSimulador = $lead->origem === 'simulador' && !empty($perfil);
                    $origemColors = [
                        'simulador'   => ['bg' => '#eff6ff', 'color' => '#2563eb', 'label' => 'Simulador'],
                        'calculadora' => ['bg' => '#fdf4ff', 'color' => '#7c3aed', 'label' => 'Calculadora'],
                        'contato'     => ['bg' => '#f0fdf4', 'color' => '#16a34a', 'label' => 'Formulário'],
                    ];
                    $origemStyle = $origemColors[$lead->origem] ?? ['bg' => '#f8fafc', 'color' => '#64748b', 'label' => ucfirst($lead->origem ?? 'direto')];
                    $perfilLabels = [
                        'situacao'          => 'Situação',
                        'faturamento_faixa' => 'Faturamento',
                        'regime'            => 'Regime',
                        'funcionarios'      => 'Funcionários CLT',
                        'prolabore'         => 'Pró-labore',
                        'nf_mes'            => 'NF/mês',
                        'complexidade'      => 'Complexidade',
                        'fidelidade'        => 'Contrato',
                    ];
                @endphp

                <div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 16px; overflow: hidden;"
                     x-data="{ expanded: false, editStatus: false, status: '{{ $lead->status }}', loading: false }">

                    <div style="padding: 1rem 1.25rem; display: flex; align-items: flex-start; gap: 1rem; flex-wrap: wrap;">

                        {{-- Expand toggle (simulator leads only) --}}
                        @if($isSimulador)
                            <button @click="expanded = !expanded"
                                    style="flex-shrink: 0; width: 28px; height: 28px; border-radius: 8px; border: 1.5px solid #e2e8f0; background: #f8fafc; cursor: pointer; display: flex; align-items: center; justify-content: center; margin-top: 2px;"
                                    :style="expanded ? 'border-color:#25b87e; background:rgba(37,184,126,0.08)' : ''"
                                    title="Ver perfil do simulador">
                                <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                                     :style="expanded ? 'transform:rotate(180deg)' : ''" style="transition:transform 0.2s;">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M19 9l-7 7-7-7"/>
                                </svg>
                            </button>
                        @endif

                        {{-- Lead identity --}}
                        <div style="min-width: 140px; flex: 1;">
                            <div style="display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;">
                                <p style="font-size: 0.9rem; font-weight: 700; color: #1e3a5f; margin: 0;">{{ $lead->name }}</p>
                                <span style="font-size: 0.6875rem; font-weight: 600; padding: 0.1875rem 0.5rem; border-radius: 100px; background: {{ $origemStyle['bg'] }}; color: {{ $origemStyle['color'] }};">
                                    {{ $origemStyle['label'] }}
                                </span>
                            </div>
                            @if($lead->company)
                                <p style="font-size: 0.75rem; color: #94a3b8; margin: 2px 0 0;">{{ $lead->company }}</p>
                            @endif
                            <p style="font-size: 0.75rem; color: #cbd5e1; margin: 2px 0 0;">{{ $lead->created_at->format('d/m/Y \à\s H:i') }}</p>
                        </div>

                        {{-- Contact --}}
                        <div style="min-width: 140px;">
                            <a href="mailto:{{ $lead->email }}" style="font-size: 0.8125rem; color: #25b87e; text-decoration: none; display: block; word-break: break-all;">{{ $lead->email }}</a>
                            @if($lead->phone)
                                <a href="https://wa.me/55{{ preg_replace('/\D/', '', $lead->phone) }}" target="_blank"
                                   style="font-size: 0.75rem; color: #64748b; text-decoration: none; display: flex; align-items: center; gap: 0.25rem; margin-top: 2px;">
                                    <svg width="11" height="11" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884"/></svg>
                                    {{ $lead->phone }}
                                </a>
                            @endif
                        </div>

                        {{-- Message --}}
                        <div style="flex: 2; min-width: 140px; max-width: 300px;">
                            <p style="font-size: 0.8125rem; color: #64748b; margin: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;">
                                {{ $lead->message }}
                            </p>
                        </div>

                        {{-- Status --}}
                        <div style="min-width: 110px;">
                            <div x-show="!editStatus" @click="editStatus = true" style="cursor: pointer;">
                                <span style="display: inline-flex; align-items: center; padding: 0.3125rem 0.75rem; border-radius: 100px; font-size: 0.75rem; font-weight: 600; background: {{ $lead->statusColor }}18; color: {{ $lead->statusColor }}; border: 1px solid {{ $lead->statusColor }}33; white-space: nowrap;"
                                      x-text="status">
                                </span>
                                <p style="font-size: 0.6875rem; color: #cbd5e1; margin: 2px 0 0;">clique para editar</p>
                            </div>
                            <div x-show="editStatus" style="display: none;">
                                <select x-model="status"
                                        @change="
                                            fetch('{{ route('leads.updateStatus', $lead) }}', {
                                                method: 'PATCH',
                                                headers: {'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}'},
                                                body: JSON.stringify({status})
                                            }).then(() => editStatus = false);
                                        "
                                        style="padding: 0.375rem 0.5rem; border: 1.5px solid #25b87e; border-radius: 8px; font-size: 0.8125rem; font-family: 'Poppins', sans-serif; color: #1e3a5f; outline: none; width: 130px;">
                                    @foreach($statuses as $s)
                                        <option value="{{ $s }}" {{ $lead->status === $s ? 'selected' : '' }}>{{ $s }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        {{-- Actions --}}
                        <div style="display: flex; gap: 0.5rem; align-items: center; flex-shrink: 0;">
                            @if(!$lead->proposta)
                                <button @click="
                                        if (!confirm('Criar proposta a partir deste lead?')) return;
                                        loading = true;
                                        fetch('{{ route('leads.proposta', $lead) }}', {
                                            method: 'POST',
                                            headers: {'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}'},
                                            body: '{}'
                                        })
                                        .then(r => r.json())
                                        .then(d => { if (d.ok) window.location.href = '{{ route('admin.propostas.index') }}'; else alert(d.message || 'Erro'); })
                                        .finally(() => loading = false);"
                                        :disabled="loading"
                                        style="display: flex; align-items: center; gap: 0.375rem; padding: 0.375rem 0.75rem; border: 1.5px solid #1e3a5f; border-radius: 8px; background: #fff; color: #1e3a5f; font-size: 0.75rem; font-weight: 600; cursor: pointer; white-space: nowrap; transition: all 0.15s;"
                                        onmouseover="this.style.background='#1e3a5f'; this.style.color='#fff';"
                                        onmouseout="this.style.background='#fff'; this.style.color='#1e3a5f';">
                                    <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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>
                                    Proposta
                                </button>
                            @else
                                <a href="{{ route('admin.propostas.index') }}"
                                   style="display: flex; align-items: center; gap: 0.375rem; padding: 0.375rem 0.75rem; border: 1.5px solid #25b87e; border-radius: 8px; background: rgba(37,184,126,0.07); color: #25b87e; font-size: 0.75rem; font-weight: 600; text-decoration: none; white-space: nowrap;">
                                    <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                    </svg>
                                    Ver proposta
                                </a>
                            @endif

                            <button onclick="if(confirm('Excluir este lead?')) fetch('{{ route('leads.destroy', $lead) }}', {method:'DELETE',headers:{'X-CSRF-TOKEN':'{{ csrf_token()}}'}}).then(()=>this.closest('[x-data]').remove())"
                                    style="padding: 0.375rem 0.5rem; border: 1px solid #fecaca; border-radius: 6px; background: #fff; color: #ef4444; font-size: 0.75rem; cursor: pointer; display: flex; align-items: center;">
                                <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                                </svg>
                            </button>
                        </div>

                    </div>

                    {{-- Expanded perfil simulador --}}
                    @if($isSimulador)
                        <div x-show="expanded"
                             x-transition:enter="transition ease-out duration-200"
                             x-transition:enter-start="opacity-0 -translate-y-1"
                             x-transition:enter-end="opacity-100 translate-y-0"
                             style="border-top: 1px solid #e8f8f1; background: #f0fdf8; padding: 1rem 1.25rem; display: none;">
                            <p style="font-size: 0.75rem; font-weight: 700; color: #25b87e; text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 0.75rem;">Perfil do simulador</p>
                            <div style="display: flex; gap: 0.625rem; flex-wrap: wrap;">
                                @foreach($perfilLabels as $key => $label)
                                    @if(!empty($perfil[$key]))
                                        <div style="background: #fff; border: 1px solid #d1fae5; border-radius: 8px; padding: 0.375rem 0.75rem;">
                                            <p style="font-size: 0.6875rem; color: #6b7280; margin: 0 0 1px; font-weight: 500;">{{ $label }}</p>
                                            <p style="font-size: 0.8125rem; font-weight: 600; color: #1e3a5f; margin: 0; text-transform: capitalize;">{{ str_replace(['-', '_'], ' ', $perfil[$key]) }}</p>
                                        </div>
                                    @endif
                                @endforeach
                            </div>
                        </div>
                    @endif

                </div>
            @endforeach
        @endif
    </div>

</x-admin-layout>
