@extends('admin.layouts.app')
@section('title', 'Lead #' . $lead->id)
@section('page-title', 'Lead Detail')

@section('content')
<nav class="flex items-center gap-2 text-sm text-gray-500 mb-6">
    <a href="{{ route('admin.leads.index') }}" class="hover:text-blue-600">Leads</a>
    <span>/</span>
    <span class="text-gray-800 font-medium">{{ $lead->name ?: $lead->phone }}</span>
</nav>

<div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
    <div class="xl:col-span-2 space-y-5">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div class="flex items-start justify-between mb-5">
                <div class="flex items-center gap-4">
                    <div class="w-14 h-14 bg-blue-600 rounded-full flex items-center justify-center text-white text-xl font-black flex-shrink-0">
                        {{ strtoupper(substr($lead->name ?: $lead->phone, 0, 1)) }}
                    </div>
                    <div>
                        <h2 class="text-xl font-bold text-gray-800">{{ $lead->name ?: 'Name not provided' }}</h2>
                        <p class="text-gray-500 text-sm">Lead #{{ $lead->id }} - {{ $lead->created_at->format('d M Y, h:i A') }}</p>
                    </div>
                </div>
                <span class="inline-flex px-3 py-1 rounded-full text-sm font-semibold {{ $lead->statusBadge() }}">
                    {{ $lead->statusLabel() }}
                </span>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
                @php
                    $info = [
                        ['Phone', $lead->phone],
                        ['Email', $lead->email ?: '-'],
                        ['Country', $lead->country_name ?: '-'],
                        ['Source', $lead->source ?: 'Direct'],
                        ['Page URL', $lead->page_url ? \Str::limit($lead->page_url, 40) : '-'],
                        ['IP', $lead->ip_address ?: '-'],
                        ['UTM Medium', $lead->utm_medium ?: '-'],
                        ['Campaign', $lead->utm_campaign ?: '-'],
                    ];
                @endphp
                @foreach($info as [$label, $value])
                    <div class="flex items-start gap-2">
                        <span class="text-gray-400 w-32 flex-shrink-0 font-medium">{{ $label }}</span>
                        <span class="text-gray-700 break-all">{{ $value }}</span>
                    </div>
                @endforeach
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 class="text-base font-bold text-gray-800 mb-5">Activity And Notes</h3>

            <div class="bg-gray-50 rounded-xl p-4 mb-6 border border-gray-100">
                <div class="flex gap-3 mb-3">
                    @foreach(['note' => 'Note', 'call' => 'Call', 'email' => 'Email', 'whatsapp' => 'WhatsApp'] as $type => $label)
                        <button type="button" onclick="selectNoteType('{{ $type }}')"
                                id="type-btn-{{ $type }}"
                                class="note-type-btn px-3 py-1.5 text-xs font-semibold rounded-lg border transition {{ $type === 'note' ? 'bg-blue-600 text-white border-blue-600' : 'bg-white text-gray-600 border-gray-200 hover:border-blue-400' }}">
                            {{ $label }}
                        </button>
                    @endforeach
                </div>
                <textarea id="note-text" rows="3" placeholder="Write your note here"
                          class="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none mb-2"></textarea>
                <button onclick="addNote({{ $lead->id }})"
                        class="bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold px-5 py-2 rounded-lg transition">
                    Add Note
                </button>
            </div>

            <div id="notes-list" class="space-y-4">
                @forelse($lead->leadNotes as $note)
                    @include('admin.leads._note', ['note' => $note])
                @empty
                    <p class="text-center text-gray-400 text-sm py-4">No notes yet. Add the first one above.</p>
                @endforelse
            </div>
        </div>
    </div>

    <div class="space-y-5">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 class="text-base font-bold text-gray-800 mb-4">Update Status</h3>
            <select id="status-select"
                    class="w-full px-4 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 mb-2">
                @foreach(['new' => 'New', 'contacted' => 'Contacted', 'enrolled' => 'Enrolled', 'rejected' => 'Rejected'] as $val => $label)
                    <option value="{{ $val }}" {{ $lead->status === $val ? 'selected' : '' }}>{{ $label }}</option>
                @endforeach
            </select>
            <button type="button" onclick="saveStatus({{ $lead->id }})"
                    class="w-full bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold py-2.5 rounded-lg transition mb-2">
                Save Status
            </button>
            <p id="status-msg" class="text-xs text-green-600 hidden">Status updated.</p>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 class="text-base font-bold text-gray-800 mb-4">Assign To</h3>
            <select id="assign-select"
                    class="w-full px-4 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">Unassigned</option>
                @foreach($employees as $emp)
                    <option value="{{ $emp->id }}" {{ $lead->assigned_to === $emp->id ? 'selected' : '' }}>
                        {{ $emp->name }} ({{ $emp->role }})
                    </option>
                @endforeach
            </select>
            <button type="button" onclick="saveAssignment({{ $lead->id }})"
                    class="w-full mt-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold py-2.5 rounded-lg transition">
                Save Assignment
            </button>
            <p id="assign-msg" class="text-xs text-green-600 mt-2 hidden">Assignment updated.</p>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 class="text-base font-bold text-gray-800 mb-4">Quick Actions</h3>
            <div class="space-y-2">
                <a href="tel:{{ $lead->phone }}"
                   class="flex items-center gap-3 p-3 rounded-lg border border-gray-100 hover:bg-blue-50 hover:border-blue-200 transition text-sm text-gray-700">
                    Call {{ $lead->phone }}
                </a>
                @if($lead->email)
                    <a href="mailto:{{ $lead->email }}"
                       class="flex items-center gap-3 p-3 rounded-lg border border-gray-100 hover:bg-blue-50 hover:border-blue-200 transition text-sm text-gray-700">
                        Email {{ $lead->email }}
                    </a>
                @endif
                <a href="https://wa.me/{{ preg_replace('/[^0-9]/', '', $lead->phone) }}" target="_blank"
                   class="flex items-center gap-3 p-3 rounded-lg border border-green-100 hover:bg-green-50 transition text-sm text-green-700">
                    WhatsApp
                </a>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <form method="POST" action="{{ route('admin.leads.destroy', $lead) }}"
                  onsubmit="return confirm('Permanently delete this lead?')">
                @csrf
                @method('DELETE')
                <button type="submit"
                        class="w-full border border-red-200 text-red-600 hover:bg-red-50 text-sm font-semibold py-2.5 rounded-lg transition">
                    Delete Lead
                </button>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
const CSRF = document.querySelector('meta[name="csrf-token"]').content;
const leadNoteUrlTemplate = @json(route('admin.leads.notes.store', ['lead' => '__LEAD__']));
const leadUpdateUrlTemplate = @json(route('admin.leads.update', ['lead' => '__LEAD__']));
const leadAssignUrlTemplate = @json(route('admin.leads.assign', ['lead' => '__LEAD__']));
let selectedNoteType = 'note';

function selectNoteType(type) {
    selectedNoteType = type;
    document.querySelectorAll('.note-type-btn').forEach(btn => {
        btn.classList.remove('bg-blue-600', 'text-white', 'border-blue-600');
        btn.classList.add('bg-white', 'text-gray-600', 'border-gray-200');
    });
    const active = document.getElementById(`type-btn-${type}`);
    active.classList.add('bg-blue-600', 'text-white', 'border-blue-600');
    active.classList.remove('bg-white', 'text-gray-600', 'border-gray-200');
}

function addNote(leadId) {
    const text = document.getElementById('note-text').value.trim();
    if (!text) {
        alert('Please write a note.');
        return;
    }

    const url = leadNoteUrlTemplate.replace('__LEAD__', String(leadId));
    fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
        body: JSON.stringify({ note: text, type: selectedNoteType }),
    })
        .then(r => r.json())
        .then(data => {
            if (!data.success) return;
            document.getElementById('note-text').value = '';
            const n = data.note;
            const empty = document.querySelector('#notes-list p.text-center');
            if (empty) empty.remove();

            const html = `
                <div class="flex gap-3 items-start">
                    <div class="w-9 h-9 bg-blue-100 rounded-full flex items-center justify-center text-sm flex-shrink-0 mt-0.5">${n.icon}</div>
                    <div class="flex-1 bg-gray-50 rounded-xl px-4 py-3 text-sm">
                        <div class="flex items-center justify-between mb-1">
                            <span class="font-semibold text-gray-700">${n.user}</span>
                            <span class="text-xs text-gray-400">${n.created_at}</span>
                        </div>
                        <p class="text-gray-600 whitespace-pre-line">${n.note}</p>
                    </div>
                </div>`;
            document.getElementById('notes-list').insertAdjacentHTML('afterbegin', html);
        });
}

function saveStatus(leadId) {
    const status = document.getElementById('status-select').value;
    const url = leadUpdateUrlTemplate.replace('__LEAD__', String(leadId));

    fetch(url, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
        body: JSON.stringify({ status }),
    })
        .then(r => r.json())
        .then(data => {
            if (!data.success) throw new Error('status update failed');
            const msg = document.getElementById('status-msg');
            msg.classList.remove('hidden');
            setTimeout(() => msg.classList.add('hidden'), 2000);
        })
        .catch(() => alert('Could not update status right now.'));
}

function saveAssignment(leadId) {
    const assignedTo = document.getElementById('assign-select').value;
    const url = leadAssignUrlTemplate.replace('__LEAD__', String(leadId));

    fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
        body: JSON.stringify({ assigned_to: assignedTo || null }),
    })
        .then(r => r.json())
        .then(data => {
            if (!data.success) throw new Error('assignment failed');
            const msg = document.getElementById('assign-msg');
            msg.classList.remove('hidden');
            setTimeout(() => msg.classList.add('hidden'), 2000);
        })
        .catch(() => alert('Could not assign lead right now.'));
}
</script>
@endpush
