@php
    /** Zaman panosu: teslim tarihine göre 4 kova. Sürükleyince son tarih güncellenir (AJAX, sayfa yenilenmez). */
    $columns = [
        'overdue' => ['label' => 'Süresi Geçenler', 'dot' => '#ef4444', 'bg' => '#fef2f2', 'icon' => 'fa-fire',          'hint' => 'Bu kolona taşıma yapılamaz'],
        'today'   => ['label' => 'Bugün Yapılacaklar', 'dot' => '#d97706', 'bg' => '#fffbeb', 'icon' => 'fa-sun',        'hint' => 'Buraya bırakılan görevin son tarihi bugüne alınır'],
        'week'    => ['label' => 'Bu Hafta İçinde', 'dot' => '#4f46e5', 'bg' => '#eef2ff', 'icon' => 'fa-calendar-week', 'hint' => 'Buraya bırakılan görevin son tarihi hafta sonuna alınır'],
        'nodate'  => ['label' => 'Süresiz Olanlar', 'dot' => '#64748b', 'bg' => '#f8fafc', 'icon' => 'fa-infinity',      'hint' => 'Buraya bırakılan görevin son tarihi kaldırılır'],
    ];
@endphp

<div class="tk-kanban tk-time" id="tkTime">
    @foreach($columns as $bucket => $col)
        <section class="tk-col" data-bucket="{{ $bucket }}">
            <header class="tk-col-head" style="--col-bg: {{ $col['bg'] }}; --col-dot: {{ $col['dot'] }};" title="{{ $col['hint'] }}">
                <span class="tk-col-dot"></span>
                <h6>{{ $col['label'] }}</h6>
                <span class="tk-col-count">{{ $time[$bucket]->count() }}</span>
            </header>

            @if($bucket === 'week' && ($time['later_count'] ?? 0) > 0)
                <div class="tk-time-later"><i class="fas fa-forward"></i> +{{ $time['later_count'] }} görev sonraki haftalarda planlı</div>
            @endif

            <div class="tk-col-body" data-bucket="{{ $bucket }}">
                @forelse($time[$bucket] as $task)
                    <article class="tk-card {{ $task->isOverdue() ? 'over' : '' }}"
                             data-id="{{ $task->id }}"
                             data-qv="{{ route('agency.tasks.quick-view', $task) }}"
                             data-time="{{ $task->due_has_time ? $task->due_date?->format('H:i') : '' }}"
                             style="--pri: {{ $task->priorityMeta()['color'] }};">
                        <div class="tk-card-top">
                            <span class="tk-badge" style="background: {{ $task->priorityMeta()['color'] }}18; color: {{ $task->priorityMeta()['color'] }};">
                                {{ $task->priorityMeta()['label'] }}
                            </span>
                            <span class="d-inline-flex align-items-center gap-1">
                                @if($task->is_auto)
                                    <span class="tk-auto-badge" title="Sistem tarafından oluşturuldu"><i class="fas fa-robot"></i></span>
                                @endif
                                <span class="tk-badge" style="background: {{ $task->statusMeta()['color'] }}18; color: {{ $task->statusMeta()['color'] }};">{{ $task->statusMeta()['label'] }}</span>
                                <button type="button" class="tk-time-done" title="Tamamlandı olarak işaretle"><i class="fas fa-check"></i></button>
                            </span>
                        </div>

                        <h5 class="tk-card-title">{{ $task->title }}</h5>

                        @if($task->relations->isNotEmpty())
                            <div class="tk-card-rels">
                                @foreach($task->relations->take(2) as $rel)
                                    <span class="tk-relchip" data-rel-qv="{{ $rel->quickViewUrl() }}" title="{{ $rel->label() }}">
                                        <i class="fas {{ $rel->meta()['icon'] }}"></i>{{ \Illuminate\Support\Str::limit($rel->label(), 26) }}
                                    </span>
                                @endforeach
                                @if($task->relations->count() > 2)
                                    <span class="tk-relchip">+{{ $task->relations->count() - 2 }}</span>
                                @endif
                            </div>
                        @endif

                        @if($task->assignees->isNotEmpty())
                            <div class="tk-people tk-card-people">
                                @foreach($task->assignees->take(2) as $user)
                                    <span class="tk-person"><span class="tk-avatar">{{ $user->initials }}</span>{{ $user->full_name }}</span>
                                @endforeach
                                @if($task->assignees->count() > 2)
                                    <span class="tk-person more" title="{{ $task->assignees->skip(2)->pluck('full_name')->implode(', ') }}">+{{ $task->assignees->count() - 2 }} kişi</span>
                                @endif
                            </div>
                        @endif

                        <div class="tk-card-foot">
                            <span class="tk-due {{ $task->isOverdue() ? 'over' : '' }}" data-due-chip>
                                @if($task->due_date)
                                    <i class="fas {{ $task->isOverdue() ? 'fa-fire' : 'fa-clock' }}"></i>
                                    {{ $task->dueLabel('d M') }}
                                @else
                                    <i class="fas fa-infinity"></i> Süresiz
                                @endif
                            </span>

                            @if(($task->comments_count ?? 0) > 0)
                                <span class="tk-due" title="{{ $task->comments_count }} not/güncelleme"><i class="far fa-comment"></i> {{ $task->comments_count }}</span>
                            @endif
                        </div>
                    </article>
                @empty
                    <div class="tk-col-empty">
                        <i class="fas {{ $col['icon'] }}"></i>
                        <span>Görev yok</span>
                    </div>
                @endforelse
            </div>
        </section>
    @endforeach
</div>

@push('styles')
<style>
    .tk-time { grid-template-columns: repeat(4, minmax(0, 1fr)); }
    .tk-kanban { display: grid; gap: 1rem; align-items: start; }
    .tk-kanban:not(.tk-time) { grid-template-columns: repeat(3, minmax(0, 1fr)); }
    .tk-col { background: #f1f5f9; border: 1px solid #e9edf3; border-radius: 16px; overflow: hidden; }
    .tk-col-head {
        display: flex; align-items: center; gap: .55rem; padding: .8rem 1rem;
        background: var(--col-bg); border-bottom: 1px solid #e9edf3;
    }
    .tk-col-dot { width: 10px; height: 10px; border-radius: 50%; background: var(--col-dot); box-shadow: 0 0 0 4px color-mix(in srgb, var(--col-dot) 18%, transparent); }
    .tk-col-head h6 { margin: 0; font-size: .84rem; font-weight: 800; color: #1e293b; letter-spacing: -0.01em; }
    .tk-col-count { margin-left: auto; font-size: .72rem; font-weight: 800; color: #64748b; background: #fff; border: 1px solid #e2e8f0; padding: .1rem .55rem; border-radius: 999px; }

    .tk-time-later {
        display: flex; align-items: center; gap: .4rem; font-size: .68rem; font-weight: 700; color: #6366f1;
        background: #eef2ff; padding: .35rem .9rem; border-bottom: 1px solid #e0e7ff;
    }

    .tk-col-body { padding: .7rem; display: flex; flex-direction: column; gap: .6rem; min-height: 200px; max-height: calc(100vh - 330px); overflow-y: auto; }
    .tk-col-body::-webkit-scrollbar { width: 5px; }
    .tk-col-body::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }

    .tk-card {
        position: relative; background: #fff; border: 1px solid #e9edf3; border-left: 4px solid var(--pri, #94a3b8);
        border-radius: 12px; padding: .75rem .85rem; cursor: pointer;
        transition: transform .15s ease, box-shadow .15s ease, opacity .25s ease;
    }
    .tk-card:hover { transform: translateY(-2px); box-shadow: 0 10px 24px -10px rgba(15,23,42,.2); }
    .tk-card.over { background: #fffafa; border-color: #fecaca; border-left-color: #ef4444; }
    .tk-card.tk-removing { opacity: 0; transform: scale(.94); }

    .tk-card-top { display: flex; align-items: center; justify-content: space-between; gap: .5rem; margin-bottom: .45rem; }
    .tk-card-title { font-size: .86rem; font-weight: 700; color: #0f172a; line-height: 1.35; margin: 0 0 .5rem; word-break: break-word; }
    .tk-card-rels { display: flex; flex-wrap: wrap; gap: .3rem; margin-bottom: .55rem; }
    .tk-card-people { margin-bottom: .55rem; }
    .tk-card-foot { display: flex; align-items: center; justify-content: space-between; gap: .5rem; }

    .tk-time-done {
        width: 24px; height: 24px; border-radius: 50%; border: 1.5px solid #d7dee9; background: #fff; color: #94a3b8;
        display: inline-flex; align-items: center; justify-content: center; font-size: .62rem; cursor: pointer;
        opacity: 0; transition: all .15s ease; flex-shrink: 0;
    }
    .tk-card:hover .tk-time-done { opacity: 1; }
    .tk-time-done:hover { background: #16a34a; border-color: #16a34a; color: #fff; }

    .tk-card.sortable-ghost { opacity: .35; background: var(--tk-soft, #fef3c7); border-style: dashed; }
    .tk-card.sortable-drag { box-shadow: 0 18px 40px -12px rgba(15,23,42,.35); transform: rotate(2deg); }

    .tk-col-empty {
        display: flex; flex-direction: column; align-items: center; justify-content: center; gap: .4rem;
        border: 2px dashed #e2e8f0; border-radius: 12px; padding: 1.6rem .5rem; color: #b6c2d2;
        font-size: .78rem; font-weight: 700;
    }
    .tk-col-empty i { font-size: 1.2rem; opacity: .6; }

    @media (max-width: 1200px) { .tk-time { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
    @media (max-width: 768px) { .tk-time { grid-template-columns: 1fr; } .tk-col-body { max-height: none; } }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
<script>
(function () {
    const CSRF = document.querySelector('meta[name="csrf-token"]')?.content;
    const FIELD_URL = @js(route('agency.tasks.update-field', ['task' => '__ID__']));
    const STATUS_URL = @js(route('agency.tasks.status', ['task' => '__ID__']));
    const COUNTS_URL = @js(route('agency.tasks.counts'));
    const MONTHS = ['Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara'];
    let dragging = false;

    const board = document.getElementById('tkTime');
    if (!board) return;

    function notify(msg, ok) {
        if (window.Swal) {
            Swal.fire({ toast: true, position: 'top-end', timer: 2200, timerProgressBar: true,
                showConfirmButton: false, icon: ok === false ? 'error' : 'success', title: msg });
        }
    }
    function patch(url, body) {
        return fetch(url, {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
            body: JSON.stringify(body)
        }).then(async r => {
            const d = await r.json().catch(() => ({}));
            if (!r.ok || d.success === false) throw new Error(d.message || 'İşlem gerçekleştirilemedi.');
            return d;
        });
    }
    const pad = n => String(n).padStart(2, '0');
    const ymd = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;

    /** Hafta sonu (Pazar) tarihi */
    function endOfWeek() {
        const d = new Date();
        const offset = (7 - d.getDay()) % 7; // Pazar = 0
        d.setDate(d.getDate() + offset);
        return d;
    }

    /** Kovaya göre yeni son tarih; kartın mevcut saati korunur, yoksa 17:00 */
    // Saat isteğe bağlı: kartta saat yoksa taşındığında da saatsiz kalır.
    function dueFor(bucket, card) {
        if (bucket === 'nodate') return '';
        const time = card.dataset.time || '';
        const d = bucket === 'today' ? new Date() : (bucket === 'week' ? endOfWeek() : null);
        if (!d) return null; // overdue vb. — tarih değişmez
        return time ? `${ymd(d)} ${time}` : ymd(d);
    }

    function chipLabel(bucket, card) {
        if (bucket === 'nodate') return '<i class="fas fa-infinity"></i> Süresiz';
        const time = card.dataset.time || '';
        const d = bucket === 'today' ? new Date() : endOfWeek();
        const label = `${d.getDate()} ${MONTHS[d.getMonth()]}` + (time ? `, ${time}` : '');
        return `<i class="fas fa-clock"></i> ${label}`;
    }

    function refreshCounts() {
        board.querySelectorAll('.tk-col').forEach(col => {
            col.querySelector('.tk-col-count').textContent = col.querySelectorAll('.tk-card').length;
        });
    }
    function refreshTopbar() {
        fetch(COUNTS_URL, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(r => r.json())
            .then(d => {
                Object.entries(d || {}).forEach(([k, v]) => {
                    const el = document.querySelector(`[data-tk-count="${k}"]`);
                    if (el) el.textContent = v;
                });
            }).catch(() => {});
    }

    board.querySelectorAll('.tk-col-body').forEach(colEl => {
        const bucket = colEl.dataset.bucket;
        new Sortable(colEl, {
            group: { name: 'tk-time', put: bucket !== 'overdue' }, // süresi geçmişe taşıma kapalı
            animation: 180,
            ghostClass: 'sortable-ghost',
            dragClass: 'sortable-drag',
            onStart: () => { dragging = true; },
            onEnd: (evt) => {
                setTimeout(() => { dragging = false; }, 80);
                const toBucket = evt.to.dataset.bucket;
                const fromBucket = evt.from.dataset.bucket;
                if (toBucket === fromBucket) return;

                const card = evt.item;
                const value = dueFor(toBucket, card);
                if (value === null) return;

                patch(FIELD_URL.replace('__ID__', card.dataset.id), { field: 'due_date', value })
                    .then(() => {
                        const chip = card.querySelector('[data-due-chip]');
                        if (chip) { chip.innerHTML = chipLabel(toBucket, card); chip.classList.remove('over'); }
                        card.classList.remove('over');
                        if (toBucket === 'nodate') card.dataset.time = '';
                        refreshCounts();
                        refreshTopbar();
                        notify('Son tarih güncellendi.');
                    })
                    .catch(err => {
                        // Sayfa yenilemeden geri al: kartı eski kolonuna, eski sırasına koy
                        const ref = evt.from.children[evt.oldIndex] || null;
                        evt.from.insertBefore(card, ref);
                        refreshCounts();
                        notify(err.message, false);
                    });
            }
        });
    });

    // Kart tıklaması → quick-view; ✓ → tamamla; chip → ilişkili kayıt
    board.addEventListener('click', (e) => {
        if (dragging) return;

        const done = e.target.closest('.tk-time-done');
        if (done) {
            e.stopPropagation();
            const card = done.closest('.tk-card');
            patch(STATUS_URL.replace('__ID__', card.dataset.id), { status: 'completed' })
                .then((d) => {
                    refreshTopbar();

                    // Onay şartlı görev kapanmaz, atayanın onayına düşer — kart
                    // panoda kalır ve kullanıcı uyarılır.
                    if (d && d.sent_to_approval) {
                        done.remove();
                        notify((d.approver || 'Görevi atayan kişi')
                            + ' onaylayana kadar görev tamamlanmış sayılmaz; onayına gönderildi.', false);
                        return;
                    }

                    card.classList.add('tk-removing');
                    setTimeout(() => { card.remove(); refreshCounts(); }, 250);
                    notify(d && d.checklist_done
                        ? `Görev tamamlandı — ${d.checklist_done} kontrol maddesi de işaretlendi.`
                        : 'Görev tamamlandı olarak işaretlendi.');
                })
                .catch(err => notify(err.message, false));
            return;
        }

        const chip = e.target.closest('[data-rel-qv]');
        if (chip) {
            e.stopPropagation();
            if (chip.dataset.relQv && typeof openQuickView === 'function') openQuickView(chip.dataset.relQv);
            return;
        }

        const card = e.target.closest('.tk-card');
        if (card && typeof openQuickView === 'function') openQuickView(card.dataset.qv);
    });
})();
</script>
@endpush
