@extends('layouts.Project')

@section('styles')
{{-- Style untuk Papan Kanban Modern --}}
<style>
    /* [BARU] Font Awesome untuk ikon (sudah ada di layout Anda) */
    /* @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css'); */

    .kanban-board {
        display: flex;
        overflow-x: auto;
        padding-bottom: 16px;
        min-height: 75vh;
        background-color: #f0f4f8; /* Latar belakang biru muda */
        border-radius: 16px;
        padding: 20px;
    }
    
    .kanban-column {
        flex: 1;
        min-width: 320px;
        max-width: 340px;
        margin: 0 10px;
        background-color: #ffffff; /* Putih bersih */
        border-radius: 12px;
        display: flex;
        flex-direction: column;
        border: 1px solid #e2e8f0;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    }
    
    .kanban-column:first-child { margin-left: 0; }
    .kanban-column:last-child { margin-right: 0; }
    
    .kanban-column-title {
        font-size: 0.9rem;
        font-weight: 600;
        text-transform: uppercase;
        color: #2c5282; /* Biru gelap */
        padding: 16px;
        border-bottom: 1px solid #e2e8f0;
        display: flex;
        align-items: center;
        background-color: #ebf4ff; /* Biru sangat muda */
        border-radius: 12px 12px 0 0;
    }
    
    .kanban-column-title span {
        margin-left: 8px;
        font-size: 0.8rem;
        background-color: #2c5282; /* Biru gelap */
        color: white;
        padding: 2px 8px;
        border-radius: 12px;
    }

    .kanban-column-body {
        flex-grow: 1;
        padding: 12px;
        min-height: 150px;
        transition: background-color 0.2s ease;
        background-color: #f7fafc; /* Biru sangat pucat */
    }
    
    .kanban-column-body.drag-over {
        background-color: #e2e8f0; /* Biru abu-abu saat drag over */
    }

    /* [DESAIN BARU] Card */
    .kanban-card {
        background-color: #ffffff;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 12px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        cursor: pointer;
        border: 1px solid #e2e8f0;
        transition: all 0.2s ease;
        position: relative; /* Untuk indikator status */
    }
    
    .kanban-card:hover {
        box-shadow: 0 8px 15px rgba(44, 82, 130, 0.15); /* Bayangan biru */
        transform: translateY(-2px);
    }
    
    .kanban-card.dragging {
        opacity: 0.5;
        transform: rotate(2deg);
        cursor: grabbing;
    }

    /* [BARU] Indikator Status di Ujung Card */
    .status-indicator {
        position: absolute;
        top: 0;
        right: 0;
        width: 8px;
        height: 100%;
        border-radius: 0 8px 8px 0;
    }
    
    .status-todo {
        background-color: #e53e3e; /* Merah untuk To Do */
    }
    
    .status-progress {
        background-color: #dd6b20; /* Kuning untuk In Progress */
    }
    
    .status-done {
        background-color: #38a169; /* Hijau untuk Done */
    }

    /* [BARU] Tags (Proyek & Prioritas) */
    .card-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        margin-bottom: 12px;
    }
    
    .card-tag {
        font-size: 0.7rem;
        font-weight: 500;
        padding: 3px 10px;
        border-radius: 12px;
        white-space: nowrap;
    }
    
    .tag-proyek {
        background-color: #ebf8ff; /* Biru sangat muda */
        color: #2b6cb0; /* Biru sedang */
        border: 1px solid #bee3f8;
    }
    
    .tag-priority-High {
        background-color: #fed7d7; /* Merah muda */
        color: #c53030; /* Merah gelap */
    }
    
    .tag-priority-Medium {
        background-color: #feebc8; /* Kuning muda */
        color: #c05621; /* Kuning gelap */
    }
    
    .tag-priority-Low {
        background-color: #e9d8fd; /* Ungu muda */
        color: #6b46c1; /* Ungu gelap */
    }

    /* [BARU] Judul Card */
    .card-title {
        font-weight: 600;
        color: #2d3748; /* Abu-abu gelap */
        margin-bottom: 16px;
        font-size: 1rem;
    }

    /* [BARU] Footer Card (Due Date & Assignee) */
    .card-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 16px;
        border-top: 1px solid #f0f4f8;
        padding-top: 12px;
    }
    
    .card-meta-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 0.75rem;
        color: #4a5568; 
    }
    
    .card-meta-item i {
        color: #4a5568;
    }
    
    .card-assignee {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    
    .card-assignee-avatar {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background-color: #2c5282; 
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.7rem;
        font-weight: 700;
        border: 2px solid white;
        box-shadow: 0 0 0 1px #2c5282;
    }

    /* Style Modal */
    .modal-overlay {
        position: fixed;
        inset: 0;
        background-color: rgba(0, 0, 0, 0.6);
        z-index: 50;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 16px;
    }
    
    .modal-content {
        background-color: white;
        border-radius: 12px;
        box-shadow: 0 10px 25px rgba(44, 82, 130, 0.2); 
        width: 100%;
        max-width: 600px;
        max-height: 90vh;
        display: flex;
        flex-direction: column;
        border: 1px solid #e2e8f0;
    }
    
    .modal-header {
        padding: 16px 24px;
        border-bottom: 1px solid #e2e8f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #ebf4ff; 
        border-radius: 12px 12px 0 0;
    }
    
    .modal-title {
        font-size: 1.25rem;
        font-weight: 600;
        color: #2c5282;
    }
    
    .modal-close-btn {
        background: none;
        border: none;
        font-size: 1.5rem;
        color: #4a5568; 
        cursor: pointer;
        transition: color 0.2s;
    }
    
    .modal-close-btn:hover {
        color: #2c5282; 
    }
    
    .modal-body {
        padding: 24px;
        overflow-y: auto;
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
    }
    
    .modal-body-full {
        grid-column: 1 / -1;
    }
    
    .modal-body-item {
        font-size: 0.875rem;
    }
    
    .modal-body-label {
        font-weight: 600;
        color: #4a5568; 
        display: block;
        margin-bottom: 4px;
    }
    
    .modal-body-value {
        color: #2d3748; 
        font-weight: 500;
    }
    
    .modal-description {
        background-color: #f7fafc; 
        padding: 12px;
        border-radius: 6px;
        min-height: 100px;
        border: 1px solid #e2e8f0;
    }

</style>
@endsection

@section('content')
<div class="space-y-8" x-data="{ showTaskModal: false, selectedTask: null }">
    <div class="flex justify-between items-center">
        <div>
            <h1 class="text-3xl font-bold text-gray-800">Progres Tim</h1>
            <p class="text-gray-500 mt-1">Pantau progres semua task secara real-time. (Drag-and-drop untuk update status)</p>
        </div>
    </div>

    {{-- Notifikasi Sukses/Error untuk AJAX --}}
    <div id="notification" class="fixed top-20 right-8 z-[100] hidden">
        <div id="notification-content" class="px-6 py-4 rounded-lg shadow-lg text-white">
            <span id="notification-message"></span>
        </div>
    </div>


    {{-- Papan Kanban --}}
    <div class="kanban-board">
        
        @php
            $statuses = [
                'To Do' => $tasksByStatus['To Do'],
                'In Progress' => $tasksByStatus['In Progress'],
                'Done' => $tasksByStatus['Done']
            ];
        @endphp

        @foreach ($statuses as $status => $tasks)
        <div class="kanban-column">
            <div class="kanban-column-title">
                {{ $status }} <span>{{ $tasks->count() }}</span>
            </div>
            <div class="kanban-column-body" data-status="{{ $status }}">
                @forelse ($tasks as $task)
                    <div class="kanban-card" 
                         draggable="true" 
                         data-task-id="{{ $task->id }}"
                         @click="selectedTask = @json($task); showTaskModal = true">
                        
                        <!-- [BARU] Indikator Status -->
                        <div class="status-indicator 
                            @if($status == 'To Do') status-todo 
                            @elseif($status == 'In Progress') status-progress 
                            @else status-done @endif">
                        </div>
                        
                        <!-- [DESAIN BARU] Tags -->
                        <div class="card-tags">
                            <span class="card-tag tag-proyek">{{ $task->proyek->nama_proyek ?? 'N/A' }}</span>
                            <span class="card-tag tag-priority-{{ $task->priority }}">{{ $task->priority }}</span>
                        </div>
                        
                        <!-- [DESAIN BARU] Judul -->
                        <div class="card-title">{{ $task->title }}</div>

                        <!-- [DESAIN BARU] Footer -->
                        <div class="card-footer">
                            <div class="card-meta-item" title="Jatuh Tempo">
                                <i class="fas fa-calendar-alt"></i>
                                <span>{{ $task->due_date ? $task->due_date->format('d M Y') : '-' }}</span>
                            </div>
                            <div class="card-assignee" title="Ditugaskan kepada {{ $task->anggota->nama ?? 'N/A' }}">
                                <span class="card-assignee-avatar">
                                    {{ $task->anggota ? strtoupper(substr($task->anggota->nama, 0, 1)) : '?' }}
                                </span>
                            </div>
                        </div>
                    </div>
                @empty
                    {{-- Kosong --}}
                @endforelse
            </div>
        </div>
        @endforeach

    </div>

    {{-- Modal Popup Detail Task (Desain disesuaikan) --}}
    <div x-show="showTaskModal" 
         @keydown.escape.window="showTaskModal = false"
         class="modal-overlay" 
         style="display: none;" 
         x-transition:enter="ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0">
        
        <div class="modal-content" 
             @click.stop
             x-show="showTaskModal"
             x-transition:enter="ease-out duration-300"
             x-transition:enter-start="opacity-0 scale-95"
             x-transition:enter-end="opacity-100 scale-100"
             x-transition:leave="ease-in duration-200"
             x-transition:leave-start="opacity-100 scale-100"
             x-transition:leave-end="opacity-0 scale-95">

            {{-- Header Modal --}}
            <div class="modal-header">
                <h2 class="modal-title" x-text="selectedTask?.title">Detail Task</h2>
                <button class="modal-close-btn" @click="showTaskModal = false">&times;</button>
            </div>

            {{-- Body Modal --}}
            <div class="modal-body" x-if="selectedTask">
                <div class="modal-body-item">
                    <span class="modal-body-label">Status</span>
                    <span class="modal-body-value" x-text="selectedTask.status"></span>
                </div>
                <div class="modal-body-item">
                    <span class="modal-body-label">Prioritas</span>
                    <span class="modal-body-value" x-text="selectedTask.priority"></span>
                </div>
                <div class="modal-body-item">
                    <span class="modal-body-label">Proyek</span>
                    <span class="modal-body-value" x-text="selectedTask.proyek?.nama_proyek || 'N/A'"></span>
                </div>
                <div class="modal-body-item">
                    <span class="modal-body-label">Jatuh Tempo</span>
                    <span class="modal-body-value" x-text="selectedTask.due_date ? new Date(selectedTask.due_date).toLocaleDateString('id-ID', { day: '2-digit', month: 'long', year: 'numeric' }) : '-'"></span>
                </div>
                <div class="modal-body-item">
                    <span class="modal-body-label">Ditugaskan Kepada</span>
                    <span class="modal-body-value" x-text="selectedTask.anggota?.nama || 'N/A'"></span>
                </div>
                <div class="modal-body-item">
                    <span class="modal-body-label">Dibuat Pada</span>
                    <span class="modal-body-value" x-text="new Date(selectedTask.created_at).toLocaleDateString('id-ID', { day: '2-digit', month: 'long', year: 'numeric' })"></span>
                </div>
                <div class="modal-body-full">
                    <span class="modal-body-label">Deskripsi</span>
                    <div class="modal-description" x-html="selectedTask.description || '<i>Tidak ada deskripsi.</i>'"></div>
                </div>
            </div>
        </div>
    </div>
    
</div>
@endsection

@section('scripts')
{{-- Script untuk Drag-and-Drop (Logika sama, aman) --}}
<script>
    document.addEventListener('DOMContentLoaded', () => {
        const cards = document.querySelectorAll('.kanban-card');
        const columns = document.querySelectorAll('.kanban-column-body');
        const notification = document.getElementById('notification');
        const notificationContent = document.getElementById('notification-content');
        const notificationMessage = document.getElementById('notification-message');

        let draggedCard = null;

        function showNotification(message, isSuccess = true) {
            notificationMessage.textContent = message;
            notificationContent.className = 'px-6 py-4 rounded-lg shadow-lg text-white ' + (isSuccess ? 'bg-green-500' : 'bg-red-500');
            notification.classList.remove('hidden');
            setTimeout(() => {
                notification.classList.add('hidden');
            }, 3000);
        }

        cards.forEach(card => {
            card.addEventListener('dragstart', (e) => {
                if (!e.target.classList.contains('kanban-card')) return;
                draggedCard = card;
                setTimeout(() => card.classList.add('dragging'), 0);
            });
            card.addEventListener('dragend', () => {
                if (draggedCard) draggedCard.classList.remove('dragging');
                draggedCard = null;
            });
        });

        columns.forEach(column => {
            column.addEventListener('dragover', e => {
                e.preventDefault();
                column.classList.add('drag-over');
            });
            column.addEventListener('dragenter', e => e.preventDefault());
            column.addEventListener('dragleave', () => column.classList.remove('drag-over'));
            column.addEventListener('drop', e => {
                e.preventDefault();
                column.classList.remove('drag-over');
                if (!draggedCard || column.contains(draggedCard)) return;

                const newStatus = column.dataset.status;
                const taskId = draggedCard.dataset.taskId;

                column.prepend(draggedCard); // Pindahkan ke atas kolom
                updateTaskStatus(taskId, newStatus, draggedCard);
            });
        });

        function updateTaskStatus(taskId, newStatus, cardElement) {
            const url = `/tasks/${taskId}/update-status`;
            const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': token,
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ status: newStatus })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('Status task diperbarui!', true);
                    updateColumnCounts(); // Panggil fungsi update count
                    updateStatusIndicator(cardElement, newStatus); // Update indikator status
                } else {
                    showNotification(data.message || 'Gagal update status.', false);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Terjadi error. Cek console.', false);
            });
        }
        
        // Fungsi untuk update jumlah task di header kolom
        function updateColumnCounts() {
            const allColumns = document.querySelectorAll('.kanban-column');
            allColumns.forEach(column => {
                const titleElement = column.querySelector('.kanban-column-title');
                const bodyElement = column.querySelector('.kanban-column-body');
                const cardCount = bodyElement.querySelectorAll('.kanban-card').length;
                const statusName = bodyElement.dataset.status;
                
                titleElement.innerHTML = `${statusName} <span>${cardCount}</span>`; // Set HTML-nya
            });
        }
        
        // [BARU] Fungsi untuk update indikator status pada card
        function updateStatusIndicator(cardElement, newStatus) {
            const indicator = cardElement.querySelector('.status-indicator');
            if (indicator) {
                // Hapus semua kelas status
                indicator.classList.remove('status-todo', 'status-progress', 'status-done');
                
                // Tambahkan kelas sesuai status baru
                if (newStatus === 'To Do') {
                    indicator.classList.add('status-todo');
                } else if (newStatus === 'In Progress') {
                    indicator.classList.add('status-progress');
                } else if (newStatus === 'Done') {
                    indicator.classList.add('status-done');
                }
            }
        }
    });
</script>
@endsection