@extends('layouts.app')
@section('title', 'Sales Pipeline — HIGHRA CRM')
@section('header', 'Sales Pipeline')

@section('content')
<!-- HEADER ACTION ROW -->
<div class="row" style="margin-bottom: 20px;">
    <div>
        <h1 style="margin: 0;">Sales Pipeline</h1>
        <p style="color: #8e9ab4; margin: 4px 0 0;">Drag and drop deals across stages or filter prospects to accelerate conversions.</p>
    </div>
    <div style="display: flex; gap: 10px; align-items: center;">
        <a href="{{ route('leads.index') }}" class="btn btn-secondary">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
            Table View
        </a>
        @if(auth()->user()?->hasPermission('leads.create'))
            <a href="{{ route('leads.create') }}" class="btn">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                + New Lead
            </a>
        @endif
    </div>
</div>

<!-- PIPELINE KPI STATS BAR -->
<div class="cards" style="grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); margin-bottom: 22px;">
    <div>
        <span style="color: #8e9ab4; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;">Total Deals</span>
        <strong>{{ $stats['total_deals'] }}</strong>
        <small style="color: #64748b; font-size: 12px;">Active & closed in pipeline</small>
    </div>
    <div>
        <span style="color: #8e9ab4; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;">Pipeline Value</span>
        <strong style="color: #38bdf8;">{{ format_inr($stats['total_value']) }}</strong>
        <small style="color: #64748b; font-size: 12px;">Total estimated deal worth</small>
    </div>
    <div>
        <span style="color: #8e9ab4; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;">Active Opportunities</span>
        <strong style="color: #a78bfa;">{{ $stats['active_deals'] }}</strong>
        <small style="color: #64748b; font-size: 12px;">In progress (excluding won/lost)</small>
    </div>
    <div>
        <span style="color: #8e9ab4; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;">Won Revenue</span>
        <strong style="color: #34d399;">{{ format_inr($stats['won_value']) }}</strong>
        <small style="color: #64748b; font-size: 12px;">{{ $stats['won_deals'] }} deals successfully closed</small>
    </div>
</div>

<!-- SEARCH & FILTER TOOLBAR -->
<form id="pipelineFilterForm" method="GET" action="{{ route('pipeline') }}">
    <div class="filter-toolbar">
        <div class="filter-grid" style="grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));">
            
            <!-- 1. Search Keyword -->
            <div class="filter-group" style="grid-column: span 2;">
                <label>Search Deals</label>
                <div style="position: relative;">
                    <input type="text" id="pipelineSearchInput" name="search" value="{{ request('search') }}" placeholder="Live search lead name, code, phone, email, or company...">
                </div>
            </div>

            <!-- 2. Assigned Executive Filter -->
            <div class="filter-group">
                <label>Assigned Executive</label>
                <select name="assigned_to" onchange="this.form.submit()">
                    <option value="">All Executives</option>
                    <option value="unassigned" {{ request('assigned_to') === 'unassigned' ? 'selected' : '' }}>Unassigned</option>
                    @foreach($users as $u)
                        <option value="{{ $u->id }}" {{ request('assigned_to') == $u->id ? 'selected' : '' }}>
                            {{ $u->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            <!-- 3. Source Filter -->
            <div class="filter-group">
                <label>Lead Source</label>
                <select name="source" onchange="this.form.submit()">
                    <option value="">All Sources</option>
                    <option value="manual" {{ request('source') == 'manual' ? 'selected' : '' }}>Manual</option>
                    <option value="facebook" {{ request('source') == 'facebook' ? 'selected' : '' }}>Facebook</option>
                    <option value="instagram" {{ request('source') == 'instagram' ? 'selected' : '' }}>Instagram</option>
                    <option value="website" {{ request('source') == 'website' ? 'selected' : '' }}>Website</option>
                    <option value="whatsapp" {{ request('source') == 'whatsapp' ? 'selected' : '' }}>WhatsApp</option>
                    <option value="referral" {{ request('source') == 'referral' ? 'selected' : '' }}>Referral</option>
                    @if(isset($sources))
                        @foreach($sources as $src)
                            @if(!in_array(strtolower($src), ['manual','facebook','instagram','website','whatsapp','referral']))
                                <option value="{{ $src }}" {{ request('source') == $src ? 'selected' : '' }}>{{ ucfirst($src) }}</option>
                            @endif
                        @endforeach
                    @endif
                </select>
            </div>

            <!-- 4. Priority Filter -->
            <div class="filter-group">
                <label>Priority</label>
                <select name="priority" onchange="this.form.submit()">
                    <option value="">All Priorities</option>
                    <option value="urgent" {{ request('priority') == 'urgent' ? 'selected' : '' }}>Urgent</option>
                    <option value="high" {{ request('priority') == 'high' ? 'selected' : '' }}>High</option>
                    <option value="normal" {{ request('priority') == 'normal' ? 'selected' : '' }}>Normal</option>
                    <option value="low" {{ request('priority') == 'low' ? 'selected' : '' }}>Low</option>
                </select>
            </div>

            <!-- 5. Actions -->
            <div class="filter-group">
                <label>&nbsp;</label>
                <div class="filter-actions">
                    <button type="submit" class="btn" style="padding: 9px 14px; font-size: 13px;">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                        Filter
                    </button>
                    @if(request()->hasAny(['search', 'assigned_to', 'source', 'priority']))
                        <a href="{{ route('pipeline') }}" class="btn btn-secondary" style="padding: 9px 12px; font-size: 13px;" title="Clear all filters">
                            ✕ Reset
                        </a>
                    @endif
                </div>
            </div>

        </div>
    </div>
</form>

<!-- KANBAN BOARD CONTAINER -->
<div class="pipeline-board-container">
    <div class="pipeline-board" id="kanbanBoard">
        
        @foreach($stages as $stageKey => $stageConfig)
            @php
                $stageLeads = $leads->where('status', $stageKey);
                $stageCount = $stageLeads->count();
                $stageValue = $stageLeads->sum('expected_value');
            @endphp
            
            <div class="pipeline-col" data-stage="{{ $stageKey }}">
                
                <!-- Column Header -->
                <div class="pipeline-col-header" style="border-top-color: {{ $stageConfig['color'] }};">
                    <div class="col-header-top">
                        <div class="col-title-wrap">
                            <span style="width: 9px; height: 9px; border-radius: 50%; background: {{ $stageConfig['color'] }};"></span>
                            <span class="col-title">{{ $stageConfig['label'] }}</span>
                        </div>
                        <span class="col-count stage-count-badge">{{ $stageCount }}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span class="col-value stage-value-sum" data-raw-val="{{ (float)$stageValue }}">
                            {{ format_inr($stageValue) }}
                        </span>
                        <small style="color: #64748b; font-size: 10px; text-transform: uppercase;">
                            {{ $stageKey === 'won' ? 'Revenue' : ($stageKey === 'lost' ? 'Lost Value' : 'Potential') }}
                        </small>
                    </div>
                </div>

                <!-- Column Drop Zone / Body -->
                <div class="pipeline-col-body col-drop-zone" data-stage="{{ $stageKey }}">
                    
                    @forelse($stageLeads as $lead)
                        <div class="pipeline-card" 
                             id="lead-card-{{ $lead->id }}" 
                             data-lead-id="{{ $lead->id }}"
                             data-search-text="{{ strtolower($lead->name . ' ' . $lead->lead_code . ' ' . $lead->phone . ' ' . $lead->email . ' ' . $lead->company) }}"
                             data-expected-val="{{ (float)($lead->expected_value ?? 0) }}"
                             draggable="true">
                            
                            <!-- Top: Name & Priority -->
                            <div class="card-top">
                                <div>
                                    <a href="{{ route('leads.show', $lead) }}" class="card-lead-name" title="View Lead Details">
                                        {{ $lead->name }}
                                    </a>
                                    <div class="card-code">{{ $lead->lead_code ?? 'LD-#'.$lead->id }}</div>
                                </div>
                                @if($lead->priority)
                                    <span class="card-priority-tag priority-{{ strtolower($lead->priority) }}">
                                        {{ ucfirst($lead->priority) }}
                                    </span>
                                @endif
                            </div>

                            <!-- Value & Source -->
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <div class="card-value">
                                    {{ $lead->expected_value ? format_inr($lead->expected_value) : '—' }}
                                </div>
                                <div class="card-tags">
                                    <span class="card-source-tag">{{ $lead->source ?? 'manual' }}</span>
                                </div>
                            </div>

                            <!-- Contact details -->
                            <div class="card-contact">
                                @if($lead->company)
                                    <div style="color: #e2e8f0; font-size: 12px; font-weight: 500;">
                                        🏢 {{ $lead->company }}
                                    </div>
                                @endif
                                @if($lead->phone)
                                    <div>
                                        <a href="tel:{{ $lead->phone }}">📞 {{ $lead->phone }}</a>
                                    </div>
                                @endif
                                @if($lead->email)
                                    <div>
                                        <a href="mailto:{{ $lead->email }}">✉️ {{ Str::limit($lead->email, 22) }}</a>
                                    </div>
                                @endif
                            </div>

                            <!-- Footer: Stage selector & Assignee selector -->
                            <div class="card-footer">
                                <!-- Quick Stage Switch -->
                                <select class="card-stage-select quick-stage-changer" data-lead-id="{{ $lead->id }}" title="Change Stage">
                                    @foreach($stages as $sk => $sc)
                                        <option value="{{ $sk }}" {{ $sk === $lead->status ? 'selected' : '' }}>
                                            {{ $sc['label'] }}
                                        </option>
                                    @endforeach
                                </select>

                                <!-- Quick Assignee Switch -->
                                <select class="card-assignee-select quick-assignee-changer" data-lead-id="{{ $lead->id }}" title="Assign Executive">
                                    <option value="">Unassigned</option>
                                    @foreach($users as $u)
                                        <option value="{{ $u->id }}" {{ $lead->assigned_to == $u->id ? 'selected' : '' }}>
                                            {{ $u->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                        </div>
                    @empty
                        <div class="pipeline-empty-column">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#475569" stroke-width="1.5" style="margin-bottom: 6px;"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="9" x2="15" y2="15"/><line x1="15" y1="9" x2="9" y2="15"/></svg>
                            <div>No deals in this stage</div>
                        </div>
                    @endforelse

                </div>

            </div>
        @endforeach

    </div>
</div>

<!-- TOAST NOTIFICATION -->
<div id="pipelineToast" class="crm-toast">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
    <span id="pipelineToastMessage">Updated successfully</span>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const csrfToken = '{{ csrf_token() }}';
    const toast = document.getElementById('pipelineToast');
    const toastMessage = document.getElementById('pipelineToastMessage');

    function showToast(message, isError = false) {
        toastMessage.textContent = message;
        if (isError) {
            toast.style.background = '#3b1822';
            toast.style.borderColor = '#5c2333';
            toast.style.color = '#ff9eb4';
        } else {
            toast.style.background = '#0f2921';
            toast.style.borderColor = '#166534';
            toast.style.color = '#4ade80';
        }
        toast.classList.add('show');
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // Helper to format currency in Indian Rupees (en-IN)
    function formatCurrency(amount) {
        return '₹' + Number(amount).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    // Recalculate column counters and sums
    function updateColumnStats(columnBody) {
        const column = columnBody.closest('.pipeline-col');
        if (!column) return;

        const cards = columnBody.querySelectorAll('.pipeline-card:not([style*="display: none"])');
        const count = cards.length;
        
        let sum = 0;
        cards.forEach(card => {
            sum += parseFloat(card.dataset.expectedVal || 0);
        });

        const badge = column.querySelector('.stage-count-badge');
        if (badge) badge.textContent = count;

        const valElem = column.querySelector('.stage-value-sum');
        if (valElem) {
            valElem.dataset.rawVal = sum;
            valElem.textContent = formatCurrency(sum);
        }

        // Toggle empty placeholder
        let emptyState = columnBody.querySelector('.pipeline-empty-column');
        if (count === 0) {
            if (!emptyState) {
                emptyState = document.createElement('div');
                emptyState.className = 'pipeline-empty-column';
                emptyState.innerHTML = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#475569" stroke-width="1.5" style="margin-bottom: 6px;"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="9" x2="15" y2="15"/><line x1="15" y1="9" x2="9" y2="15"/></svg><div>No deals in this stage</div>';
                columnBody.appendChild(emptyState);
            }
            emptyState.style.display = 'block';
        } else if (emptyState) {
            emptyState.style.display = 'none';
        }
    }

    // AJAX Call to update lead
    async function updateLeadPipeline(leadId, payload, successMsg) {
        try {
            const res = await fetch(`/pipeline/leads/${leadId}`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify(payload)
            });

            const data = await res.json();
            if (res.ok && data.ok) {
                showToast(successMsg || 'Lead updated successfully.');
                return true;
            } else {
                showToast(data.message || 'Failed to update lead.', true);
                return false;
            }
        } catch (err) {
            console.error('Update error:', err);
            showToast('Network error while updating.', true);
            return false;
        }
    }

    // --- 1. DRAG AND DROP IMPLEMENTATION ---
    let draggedCard = null;
    let sourceColumn = null;

    document.querySelectorAll('.pipeline-card').forEach(card => {
        card.addEventListener('dragstart', (e) => {
            draggedCard = card;
            sourceColumn = card.closest('.pipeline-col-body');
            card.classList.add('is-dragging');
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/plain', card.dataset.leadId);
        });

        card.addEventListener('dragend', () => {
            card.classList.remove('is-dragging');
            document.querySelectorAll('.col-drop-zone').forEach(z => z.classList.remove('drag-over'));
            draggedCard = null;
            sourceColumn = null;
        });
    });

    document.querySelectorAll('.col-drop-zone').forEach(dropZone => {
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            dropZone.classList.add('drag-over');
        });

        dropZone.addEventListener('dragleave', (e) => {
            if (!dropZone.contains(e.relatedTarget)) {
                dropZone.classList.remove('drag-over');
            }
        });

        dropZone.addEventListener('drop', async (e) => {
            e.preventDefault();
            dropZone.classList.remove('drag-over');

            if (!draggedCard) return;

            const targetStage = dropZone.dataset.stage;
            const leadId = draggedCard.dataset.leadId;
            const oldColumn = sourceColumn;

            if (dropZone === oldColumn) return;

            // Move in DOM immediately for snappy feedback
            dropZone.appendChild(draggedCard);

            // Update stage selector inside the card
            const stageSelect = draggedCard.querySelector('.quick-stage-changer');
            if (stageSelect) stageSelect.value = targetStage;

            // Update stats on both old and new columns
            if (oldColumn) updateColumnStats(oldColumn);
            updateColumnStats(dropZone);

            // Fire AJAX
            const ok = await updateLeadPipeline(leadId, { status: targetStage }, `Moved to ${targetStage.toUpperCase()}`);
            if (!ok && oldColumn) {
                // Revert on failure
                oldColumn.appendChild(draggedCard);
                if (stageSelect) stageSelect.value = oldColumn.dataset.stage;
                updateColumnStats(oldColumn);
                updateColumnStats(dropZone);
            }
        });
    });

    // --- 2. QUICK STAGE SELECTOR (DROPDOWN) ---
    document.querySelectorAll('.quick-stage-changer').forEach(select => {
        select.addEventListener('change', async () => {
            const leadId = select.dataset.leadId;
            const targetStage = select.value;
            const card = document.getElementById(`lead-card-${leadId}`);
            if (!card) return;

            const oldColumn = card.closest('.pipeline-col-body');
            const targetColumn = document.querySelector(`.pipeline-col-body[data-stage="${targetStage}"]`);

            if (targetColumn && targetColumn !== oldColumn) {
                targetColumn.appendChild(card);
                if (oldColumn) updateColumnStats(oldColumn);
                updateColumnStats(targetColumn);
            }

            await updateLeadPipeline(leadId, { status: targetStage }, `Stage changed to ${targetStage.toUpperCase()}`);
        });
    });

    // --- 3. QUICK ASSIGNEE SELECTOR (DROPDOWN) ---
    document.querySelectorAll('.quick-assignee-changer').forEach(select => {
        select.addEventListener('change', async () => {
            const leadId = select.dataset.leadId;
            const assignedTo = select.value || null;
            await updateLeadPipeline(leadId, { assigned_to: assignedTo }, 'Assignee updated successfully.');
        });
    });

    // --- 4. LIVE CLIENT-SIDE SEARCH AS YOU TYPE ---
    const searchInput = document.getElementById('pipelineSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', () => {
            const query = searchInput.value.trim().toLowerCase();
            document.querySelectorAll('.pipeline-card').forEach(card => {
                const text = card.dataset.searchText || '';
                if (!query || text.includes(query)) {
                    card.style.display = 'flex';
                } else {
                    card.style.display = 'none';
                }
            });

            // Update all column counters based on filtered visibility
            document.querySelectorAll('.pipeline-col-body').forEach(colBody => {
                updateColumnStats(colBody);
            });
        });
    }
});
</script>
@endsection
