@extends('layouts.app')

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

@section('content')
    @include('leads.partials.status-colors')
    <style>
        .lead-board-page { padding-top: 20px; }
        .lead-board-stats .card { border: 1px solid #e7eaf0; border-radius: 13px; box-shadow: 0 7px 22px rgba(15, 23, 42, .045); }
        .lead-board-stat-icon { display: inline-flex; width: 42px; height: 42px; align-items: center; justify-content: center; border-radius: 12px; font-size: 17px; }
        .lead-board-shell { border: 1px solid #e7eaf0; border-radius: 14px; background: #f6f8fc; box-shadow: 0 9px 28px rgba(15, 23, 42, .05); overflow: hidden; }
        .lead-board-toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 14px; padding: 18px 20px; border-bottom: 1px solid #e5e9f0; background: #fff; }
        .lead-board-scroll { overflow-x: auto; padding: 18px; }
        .lead-kanban { display: flex; align-items: flex-start; gap: 14px; min-width: max-content; }
        .lead-stage-column { width: 292px; border: 1px solid #e4e8ef; border-radius: 12px; background: #eef1f6; overflow: hidden; }
        .lead-stage-column[data-terminal="qualified"] { background: #eef8f2; border-color: #cae8d6; }
        .lead-stage-column[data-terminal="unqualified"] { background: #fff2f3; border-color: #f2d1d5; }
        .lead-stage-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px; border-bottom: 1px solid rgba(148, 163, 184, .22); background: rgba(255, 255, 255, .72); }
        .lead-stage-title { color: #253047; font-size: 13px; font-weight: 750; }
        .lead-stage-count { display: inline-flex; min-width: 25px; height: 25px; align-items: center; justify-content: center; padding: 0 7px; border-radius: 999px; background: #e2e7f0; color: #526072; font-size: 11px; font-weight: 700; }
        .lead-list { min-height: 170px; padding: 10px; }
        .lead-list.sortable-ghost-zone { background: rgba(52, 84, 209, .06); }
        .pipeline-lead-card { position: relative; margin-bottom: 10px; padding: 14px; border: 1px solid #e4e8ef; border-radius: 11px; background: #fff; box-shadow: 0 4px 14px rgba(15, 23, 42, .045); cursor: grab; transition: border-color .16s ease, box-shadow .16s ease, transform .16s ease; }
        .pipeline-lead-card:hover { border-color: #bac6e8; box-shadow: 0 8px 20px rgba(15, 23, 42, .08); transform: translateY(-1px); }
        .pipeline-lead-card.is-locked { cursor: default; }
        .pipeline-lead-card.is-locked::before { content: ''; position: absolute; inset: 0 auto 0 0; width: 3px; border-radius: 11px 0 0 11px; background: #64748b; }
        .pipeline-lead-card.is-qualified::before { background: #198754; }
        .pipeline-lead-card.is-unqualified::before { background: #dc3545; }
        .pipeline-lead-title { color: #172033; font-size: 13px; font-weight: 700; line-height: 1.35; }
        .pipeline-lead-title:hover { color: #3454d1; }
        .pipeline-lead-meta { display: flex; align-items: center; gap: 7px; margin-top: 8px; color: #64748b; font-size: 11px; }
        .pipeline-owner-avatar { display: inline-flex; width: 27px; height: 27px; align-items: center; justify-content: center; border-radius: 50%; background: #eef2ff; color: #3454d1; font-size: 9px; font-weight: 750; }
        .pipeline-empty { display: flex; min-height: 145px; flex-direction: column; align-items: center; justify-content: center; color: #94a3b8; text-align: center; font-size: 11px; }
        .pipeline-empty i { margin-bottom: 7px; font-size: 20px; }
        .sortable-ghost { opacity: .45; }
        .sortable-drag { transform: rotate(1deg); box-shadow: 0 14px 30px rgba(15, 23, 42, .15); }
        @media (max-width: 767.98px) {
            .lead-board-page { padding-top: 12px; }
            .lead-board-scroll { padding: 12px; }
            .lead-stage-column { width: 274px; }
        }
    </style>

    <div class="page-header">
        <div class="page-header-left d-flex align-items-center">
            <div class="page-header-title">
                <h5 class="mb-1">Lead Pipeline</h5>
                <small class="text-muted d-none d-lg-block">Move active Leads through each qualification stage</small>
            </div>
        </div>
        <div class="page-header-right ms-auto">
            <div class="page-header-right-items">
                <div class="d-flex d-md-none">
                    <a href="javascript:void(0)" class="page-header-right-close-toggle"><i class="feather-arrow-left me-2"></i>Back</a>
                </div>
                <div class="d-flex align-items-center gap-2 page-header-right-items-wrapper">
                    <div class="dropdown">
                        <button class="btn btn-icon btn-light-brand" type="button" data-bs-toggle="dropdown" title="Change view" aria-label="Change view">
                            <i class="feather-grid"></i>
                        </button>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a href="{{ route('leads') }}" class="dropdown-item"><i class="feather-list me-3"></i>Table View</a>
                            <a href="{{ route('leads-dashboard') }}" class="dropdown-item active"><i class="feather-grid me-3"></i>Dashboard View</a>
                        </div>
                    </div>
                    <div class="dropdown">
                        <button class="btn btn-icon btn-light-brand" type="button" data-bs-toggle="dropdown" title="Export Leads" aria-label="Export Leads">
                            <i class="feather-download"></i>
                        </button>
                        <div class="dropdown-menu dropdown-menu-end">
                            @foreach (['pdf' => 'PDF', 'csv' => 'CSV', 'xlsx' => 'Excel', 'xml' => 'XML', 'txt' => 'Text'] as $format => $label)
                                <a href="{{ route('leads.export', ['format' => $format]) }}" class="dropdown-item">
                                    <i class="feather-file-text me-3"></i>{{ $label }}
                                </a>
                            @endforeach
                        </div>
                    </div>
                    @if((int) auth()->user()->is_admin === 1 || auth()->user()->can('create_leads'))
                        <a href="{{ route('leads-create') }}" class="btn btn-primary"><i class="feather-plus me-2"></i>Create Lead</a>
                    @endif
                </div>
            </div>
            <div class="d-md-none d-flex align-items-center">
                <a href="javascript:void(0)" class="page-header-right-open-toggle"><i class="feather-align-right fs-20"></i></a>
            </div>
        </div>
    </div>

    <div class="main-content lead-board-page">
        <div class="row g-3 lead-board-stats mb-4">
            @foreach ([
                ['Total Leads', $dashboardStats['total'], 'users', 'primary'],
                ['Active Pipeline', $dashboardStats['active'], 'activity', 'info'],
                ['Qualified', $dashboardStats['qualified'], 'check-circle', 'success'],
                ['Unqualified', $dashboardStats['unqualified'], 'x-circle', 'danger'],
            ] as [$label, $value, $icon, $colour])
                <div class="col-sm-6 col-xl-3">
                    <div class="card mb-0 h-100">
                        <div class="card-body d-flex align-items-center justify-content-between gap-3 p-3">
                            <div><small class="text-muted fw-semibold">{{ $label }}</small><div class="fs-4 fw-bold text-dark mt-1">{{ number_format($value) }}</div></div>
                            <span class="lead-board-stat-icon bg-soft-{{ $colour }} text-{{ $colour }}"><i class="feather-{{ $icon }}"></i></span>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>

        <section class="lead-board-shell">
            <div class="lead-board-toolbar">
                <div>
                    <h6 class="fw-bold mb-1">Qualification Pipeline</h6>
                    <small class="text-muted">Drag active Lead cards between stages. Completed cards are locked.</small>
                </div>
                <span class="badge bg-soft-primary text-primary px-3 py-2"><i class="feather-columns me-1"></i>{{ $stages->count() }} stages</span>
            </div>
            <div class="lead-board-scroll">
                <div class="lead-kanban">
                    @foreach ($stages as $stage)
                        @php
                            $stageLeads = collect($leads->get($stage->id, []));
                            $terminalType = (int) $stage->id === 6 ? 'qualified' : ((int) $stage->id === 7 ? 'unqualified' : null);
                        @endphp
                        <section class="lead-stage-column" data-stage-id="{{ $stage->id }}" @if($terminalType) data-terminal="{{ $terminalType }}" @endif>
                            <header class="lead-stage-header">
                                <div class="d-flex align-items-center gap-2">
                                    <i class="{{ $terminalType ? ($terminalType === 'qualified' ? 'feather-check-circle text-success' : 'feather-x-circle text-danger') : 'feather-circle text-primary' }} fs-12"></i>
                                    <span class="lead-stage-title">{{ $stage->name }}</span>
                                </div>
                                <span class="lead-stage-count">{{ $stageLeads->count() }}</span>
                            </header>
                            <div class="lead-list" data-stage-id="{{ $stage->id }}">
                                @foreach ($stageLeads as $lead)
                                    @php $isCompletedLead = in_array((int) $lead->stage_id, [6, 7], true) || $lead->status === 'completed'; @endphp
                                    <article @class([
                                            'pipeline-lead-card', 'single-lead-item',
                                            'is-locked' => $isCompletedLead,
                                            'is-qualified' => (int) $lead->stage_id === 6,
                                            'is-unqualified' => (int) $lead->stage_id === 7,
                                        ]) data-lead-id="{{ $lead->id }}" data-current-stage="{{ $lead->stage_id }}">
                                        <div class="d-flex align-items-start justify-content-between gap-2">
                                            <div class="min-w-0">
                                                <a href="{{ route('leads.view', ['id' => $lead->id]) }}" class="pipeline-lead-title d-block text-truncate">{{ $lead->topic ?: 'Untitled Lead' }}</a>
                                                <small class="text-muted">Lead #{{ str_pad((string) $lead->id, 4, '0', STR_PAD_LEFT) }}</small>
                                            </div>
                                            @if ($isCompletedLead)
                                                <span class="badge {{ (int) $lead->stage_id === 6 ? 'bg-soft-success text-success' : 'bg-soft-danger text-danger' }}"><i class="feather-lock fs-9"></i></span>
                                            @elseif ($lead->priority?->name)
                                                <span class="badge bg-soft-warning text-warning">{{ $lead->priority->name }}</span>
                                            @endif
                                        </div>
                                        <div class="pipeline-lead-meta"><i class="feather-user"></i><span class="text-truncate">{{ trim(($lead->first_name ?? '').' '.($lead->last_name ?? '')) ?: 'No contact name' }}</span></div>
                                        <div class="pipeline-lead-meta"><i class="feather-briefcase"></i><span class="text-truncate">{{ $lead->company?->name ?: 'No company' }}</span></div>
                                        <div class="d-flex align-items-center justify-content-between gap-2 mt-3 pt-2 border-top">
                                            <div class="d-flex align-items-center gap-2 min-w-0">
                                                <span class="pipeline-owner-avatar">{{ strtoupper(substr($lead->assignedUser?->name ?: 'NA', 0, 2)) }}</span>
                                                <small class="text-muted text-truncate">{{ $lead->assignedUser?->name ?: 'Not assigned' }}</small>
                                            </div>
                                            <div class="d-flex align-items-center gap-1">
                                                <a href="{{ route('leads.view', ['id' => $lead->id]) }}" class="avatar-text avatar-sm" title="View Lead"><i class="feather-eye"></i></a>
                                                @if (!$isCompletedLead)
                                                    @can('update_leads')
                                                        <a href="{{ route('leads.edit', ['id' => $lead->id]) }}" class="avatar-text avatar-sm" title="Edit Lead"><i class="feather-edit-3"></i></a>
                                                    @endcan
                                                @endif
                                            </div>
                                        </div>
                                    </article>
                                @endforeach
                                @if ($stageLeads->isEmpty())
                                    <div class="pipeline-empty"><i class="feather-inbox"></i><span>No Leads in this stage</span></div>
                                @endif
                            </div>
                        </section>
                    @endforeach
                </div>
            </div>
        </section>
    </div>
@endsection

@section('scripts')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            if (typeof Sortable === 'undefined') return;

            document.querySelectorAll('.lead-list').forEach(function (list) {
                new Sortable(list, {
                    group: 'lead-pipeline',
                    animation: 180,
                    draggable: '.pipeline-lead-card:not(.is-locked)',
                    filter: '.is-locked',
                    ghostClass: 'sortable-ghost',
                    dragClass: 'sortable-drag',
                    onEnd: async function (event) {
                        if (event.from === event.to) return;

                        const card = event.item;
                        const leadId = card.dataset.leadId;
                        const previousStageId = card.dataset.currentStage;
                        const newStageId = event.to.dataset.stageId;
                        const unqualifiedReason = String(newStageId) === '7'
                            ? window.prompt('Please enter the Unqualified reason:')
                            : null;

                        if (String(newStageId) === '7' && !unqualifiedReason) {
                            window.location.reload();
                            return;
                        }

                        try {
                            const response = await fetch(`/leads/${leadId}/update-lead-stage`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'Accept': 'application/json',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                                },
                                body: JSON.stringify({ stage_id: newStageId, unqualified_reason: unqualifiedReason }),
                            });
                            const data = await response.json().catch(() => ({}));
                            if (!response.ok) throw new Error(data.message || 'Unable to update Lead Status.');
                            card.dataset.currentStage = String(data.stage_id || newStageId);
                            window.location.reload();
                        } catch (error) {
                            window.alert(error.message);
                            window.location.reload();
                        }
                    },
                });
            });
        });
    </script>
@endsection
