@extends('employee.layouts.app')
@section('title', 'Lead - ' . ($lead->name ?: $lead->phone))
@section('page-title', 'Lead Detail')

@section('content')
<nav class="flex items-center gap-2 text-sm text-gray-500 mb-6">
    <a href="{{ route('employee.leads.index') }}" class="hover:text-blue-600">My 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-center gap-4 mb-5">
                <div class="w-14 h-14 bg-gray-800 rounded-full flex items-center justify-center text-white text-xl font-black">
                    {{ 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') }}</p>
                </div>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
                @foreach([
                    ['Phone', $lead->phone],
                    ['Email', $lead->email ?: '-'],
                    ['Country', $lead->country_name ?: '-'],
                    ['Source', $lead->source ?: 'Direct'],
                ] as [$label, $value])
                    <div class="flex gap-2">
                        <span class="text-gray-400 w-28 flex-shrink-0">{{ $label }}</span>
                        <span class="text-gray-700">{{ $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-5 border border-gray-100">
                <div class="flex gap-2 mb-3 flex-wrap">
                    @foreach(['note' => 'Note', 'call' => 'Call', 'email' => 'Email', 'whatsapp' => 'WhatsApp'] as $type => $label)
                        <button type="button" onclick="selectType('{{ $type }}')"
                                id="type-{{ $type }}"
                                class="note-type px-3 py-1.5 text-xs font-semibold rounded-lg border transition {{ $type === 'note' ? 'bg-gray-800 text-white border-gray-800' : 'bg-white text-gray-600 border-gray-200 hover:border-gray-400' }}">
                            {{ $label }}
                        </button>
                    @endforeach
                </div>
                <textarea id="note-input" rows="3" placeholder="Add your note"
                          class="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 resize-none mb-2"></textarea>
                <button onclick="submitNote({{ $lead->id }})"
                        class="bg-gray-800 hover:bg-gray-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)
                    <div class="flex gap-3 items-start">
                        <div class="w-9 h-9 bg-gray-100 rounded-full flex items-center justify-center text-sm flex-shrink-0">{{ $note->typeIcon() }}</div>
                        <div class="flex-1 bg-gray-50 rounded-xl px-4 py-3 text-sm">
                            <div class="flex justify-between mb-1">
                                <span class="font-semibold text-gray-700">{{ $note->user->name }}</span>
                                <span class="text-xs text-gray-400">{{ $note->created_at->diffForHumans() }}</span>
                            </div>
                            <p class="text-gray-600">{{ $note->note }}</p>
                        </div>
                    </div>
                @empty
                    <p class="text-gray-400 text-sm text-center py-4">No notes yet.</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"
                    onchange="toggleRejectReason()"
                    class="w-full px-4 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400">
                @foreach(['contacted' => 'Contacted', 'enrolled' => 'Enrolled', 'rejected' => 'Rejected'] as $val => $label)
                    <option value="{{ $val }}" {{ $lead->status === $val ? 'selected' : '' }}>{{ $label }}</option>
                @endforeach
            </select>
            <div id="reject-reason-wrap" class="mt-2 {{ $lead->status === 'rejected' ? '' : 'hidden' }}">
                <textarea id="reject-reason" rows="3"
                          class="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-400 resize-none"
                          placeholder="Why rejected?">{{ old('rejection_reason') }}</textarea>
                <p class="text-xs text-gray-500 mt-1">Rejection reason is required.</p>
            </div>
            <button type="button" onclick="saveStatus({{ $lead->id }})"
                    class="w-full mt-2 bg-gray-800 hover:bg-gray-700 text-white text-sm font-semibold py-2.5 rounded-lg transition">
                Save Status
            </button>
            <p id="status-ok" class="text-xs text-green-600 mt-2 hidden">Updated.</p>
        </div>

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

@push('scripts')
<script>
const CSRF = document.querySelector('meta[name="csrf-token"]').content;
const employeeLeadNoteUrlTemplate = @json(route('employee.leads.notes.store', ['lead' => '__LEAD__']));
const employeeLeadStatusUrlTemplate = @json(route('employee.leads.status', ['lead' => '__LEAD__']));
let selectedType = 'note';

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

function submitNote(leadId) {
    const text = document.getElementById('note-input').value.trim();
    if (!text) return;
    const url = employeeLeadNoteUrlTemplate.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: selectedType }),
    }).then(r => r.json()).then(d => {
        if (!d.success) return;
        document.getElementById('note-input').value = '';
        const n = d.note;
        const html = `<div class="flex gap-3 items-start">
            <div class="w-9 h-9 bg-gray-100 rounded-full flex items-center justify-center text-sm flex-shrink-0">${n.icon}</div>
            <div class="flex-1 bg-gray-50 rounded-xl px-4 py-3 text-sm">
                <div class="flex 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">${n.note}</p>
            </div>
        </div>`;
        const empty = document.querySelector('#notes-list p');
        if (empty) empty.remove();
        document.getElementById('notes-list').insertAdjacentHTML('afterbegin', html);
    });
}

function saveStatus(leadId) {
    const status = document.getElementById('status-select').value;
    const rejectionReason = (document.getElementById('reject-reason')?.value || '').trim();
    if (status === 'rejected' && !rejectionReason) {
        alert('Please provide a rejection reason.');
        return;
    }
    const url = employeeLeadStatusUrlTemplate.replace('__LEAD__', String(leadId));

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

function toggleRejectReason() {
    const status = document.getElementById('status-select').value;
    const wrap = document.getElementById('reject-reason-wrap');
    if (!wrap) return;
    if (status === 'rejected') {
        wrap.classList.remove('hidden');
    } else {
        wrap.classList.add('hidden');
    }
}

toggleRejectReason();
</script>
@endpush
