<x-app-layout>
    <x-slot name="title">Lead Pipeline</x-slot>
    <div class="mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Lead Pipeline</h1>
            <p class="text-sm text-gray-500 mt-1">Drag and drop leads to update their status.</p>
        </div>
        
        <div class="flex items-center gap-3">
            <a href="{{ route('leads.index') }}" class="inline-flex items-center justify-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50 focus:outline-none transition-colors">
                <svg class="h-4 w-4 mr-1.5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"></path></svg>
                List View
            </a>
            <a href="{{ route('leads.create') }}" class="inline-flex items-center justify-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-lg text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-colors">
                + Add Lead
            </a>
        </div>
    </div>

    <!-- Kanban Board -->
    <div class="flex overflow-x-auto pb-8 -mx-4 px-4 sm:mx-0 sm:px-0 gap-6" style="min-height: calc(100vh - 200px);">
        @foreach($statuses as $status)
        <div class="flex-shrink-0 w-80 bg-gray-50/50 rounded-xl border border-gray-200 flex flex-col">
            <div class="p-4 border-b border-gray-200 flex justify-between items-center bg-white rounded-t-xl">
                <h3 class="font-semibold text-gray-800">{{ $status->name }}</h3>
                <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-gray-100 text-xs font-medium text-gray-600 border border-gray-200" id="count-{{ Str::slug($status->name) }}">
                    {{ count($leadsByStatus[$status->name] ?? []) }}
                </span>
            </div>
            
            <div class="p-3 flex-1 overflow-y-auto sortable-list" data-status="{{ $status->name }}" id="list-{{ Str::slug($status->name) }}">
                @foreach($leadsByStatus[$status->name] ?? [] as $lead)
                <div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200 mb-3 cursor-grab hover:border-primary-300 hover:shadow transition-all" data-id="{{ $lead->id }}">
                    <div class="flex justify-between items-start mb-2">
                        <a href="{{ route('leads.show', $lead) }}" class="font-medium text-gray-900 hover:text-primary-600">{{ $lead->name }}</a>
                        @if($lead->priority)
                        <span class="px-2 py-0.5 rounded text-xs font-medium
                            @if($lead->priority === 'High') bg-red-100 text-red-800
                            @elseif($lead->priority === 'Medium') bg-amber-100 text-amber-800
                            @else bg-blue-100 text-blue-800 @endif">
                            {{ $lead->priority }}
                        </span>
                        @endif
                    </div>
                    <div class="text-sm text-gray-500 mb-2 truncate">{{ $lead->email }}</div>
                    <div class="text-sm text-gray-500 mb-3">{{ $lead->phone }}</div>
                    <div class="flex justify-between items-center text-xs text-gray-400">
                        <span>{{ $lead->source->name ?? 'Unknown' }}</span>
                        <span>{{ $lead->created_at->format('M d') }}</span>
                    </div>
                </div>
                @endforeach
            </div>
        </div>
        @endforeach
    </div>

    <!-- Include SortableJS -->
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const lists = document.querySelectorAll('.sortable-list');
            
            lists.forEach(list => {
                new Sortable(list, {
                    group: 'pipeline',
                    animation: 150,
                    ghostClass: 'bg-gray-100',
                    dragClass: 'opacity-50',
                    onEnd: function(evt) {
                        const item = evt.item;
                        const toList = evt.to;
                        const fromList = evt.from;
                        
                        if (toList === fromList) return; // Didn't change column
                        
                        const leadId = item.dataset.id;
                        const newStatus = toList.dataset.status;
                        
                        // Update counts
                        const toCountEl = document.getElementById('count-' + toList.id.replace('list-', ''));
                        const fromCountEl = document.getElementById('count-' + fromList.id.replace('list-', ''));
                        
                        toCountEl.innerText = parseInt(toCountEl.innerText) + 1;
                        fromCountEl.innerText = parseInt(fromCountEl.innerText) - 1;
                        
                        // Send AJAX request
                        fetch(`{{ url('leads') }}/${leadId}/status`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                'Accept': 'application/json'
                            },
                            body: JSON.stringify({ status: newStatus })
                        })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (!data.success) {
                                alert('Failed to update status');
                            }
                        })
                        .catch(error => {
                            console.error('Error updating status:', error);
                            alert('An error occurred while saving the status change.');
                            // Optionally revert the drag if it fails
                        });
                    }
                });
            });
        });
    </script>
</x-app-layout>
