@extends('layouts.app')

@section('title', 'Pipeline')
@section('heading', 'Pipeline')

@section('content')
    <p style="font-size:0.9rem;color:var(--muted);margin-bottom:1rem">Drag cards between columns to update stage.</p>
    <div class="kanban">
        @foreach ($stages as $stage)
            <div class="kanban-column" data-stage-id="{{ $stage->id }}">
                <div class="kanban-column-header">
                    <span style="width:10px;height:10px;border-radius:50%;background:{{ $stage->color ?? '#94a3b8' }}"></span>
                    {{ $stage->name }}
                    <span class="badge">{{ $stage->leads->count() }}</span>
                </div>
                <div class="kanban-cards" data-stage-id="{{ $stage->id }}">
                    @foreach ($stage->leads as $lead)
                        <div class="kanban-card" data-lead-id="{{ $lead->id }}">
                            <a href="{{ route('leads.show', $lead) }}" style="color:inherit;font-weight:600">{{ $lead->name }}</a>
                            <div class="kanban-card-meta">
                                {{ $lead->assignee->name ?? 'Unassigned' }}
                                @if ($lead->source) · {{ $lead->source }} @endif
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        @endforeach
    </div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js" crossorigin="anonymous"></script>
<script>
(function () {
    var token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    var appBase = @json(rtrim(url('/'), '/'));
    var columns = document.querySelectorAll('.kanban-cards');
    columns.forEach(function (col) {
        Sortable.create(col, {
            group: 'leads',
            animation: 150,
            draggable: '.kanban-card',
            onEnd: function (evt) {
                var toStage = evt.to.getAttribute('data-stage-id');
                var fromStage = evt.from.getAttribute('data-stage-id');
                if (toStage === fromStage) return;
                var leadId = evt.item.getAttribute('data-lead-id');
                fetch(appBase + '/leads/' + leadId + '/stage', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': token,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ pipeline_stage_id: parseInt(toStage, 10) })
                }).then(function (r) {
                    if (!r.ok) alert('Could not update stage.');
                }).catch(function () {
                    alert('Network error.');
                });
            }
        });
    });
})();
</script>
@endpush
