@extends('layouts.app')

@section('content')
<div class="mb-8 h-full flex flex-col">
    <div class="flex items-center justify-between mb-8">
        <div>
            <h1 class="text-3xl font-extrabold text-gray-900 tracking-tight">Today's Tasks</h1>
            <p class="mt-1 text-sm text-gray-500 font-medium">{{ \Carbon\Carbon::today()->format('l, F jS, Y') }}</p>
        </div>
    </div>

    <div class="flex-1 flex gap-4 sm:gap-6 overflow-x-auto pb-4 snap-x snap-mandatory">
        <!-- Columns -->
        @foreach([
            ['id' => 'todo', 'title' => 'To Do', 'tasks' => $todo, 'color' => 'bg-gray-100 border-gray-200', 'badge' => 'bg-gray-200 text-gray-800'],
            ['id' => 'doing', 'title' => 'Doing', 'tasks' => $doing, 'color' => 'bg-blue-50 border-blue-100', 'badge' => 'bg-blue-200 text-blue-800'],
            ['id' => 'done', 'title' => 'Done', 'tasks' => $done, 'color' => 'bg-green-50 border-green-100', 'badge' => 'bg-green-200 text-green-800'],
            ['id' => 'tomorrow', 'title' => 'Tomorrow', 'tasks' => $tomorrow, 'color' => 'bg-purple-50 border-purple-100', 'badge' => 'bg-purple-200 text-purple-800']
        ] as $column)
        <div class="flex-shrink-0 w-[85vw] sm:w-80 flex flex-col rounded-xl border {{ $column['color'] }} snap-start">
            <div class="px-4 py-3 border-b border-black/5 flex justify-between items-center rounded-t-xl bg-white/50 backdrop-blur-sm">
                <h3 class="text-sm font-bold text-gray-700 uppercase tracking-wider">{{ $column['title'] }}</h3>
                <span class="px-2 py-0.5 rounded-full text-xs font-bold {{ $column['badge'] }} task-count-{{ $column['id'] }}">{{ $column['tasks']->count() }}</span>
            </div>
            
            <div class="p-3 flex-1 overflow-y-auto space-y-3 min-h-[500px] kanban-column transition-colors duration-200" data-status="{{ $column['id'] }}">
                @foreach($column['tasks'] as $task)
                    <div data-id="{{ $task->id }}" class="kanban-task p-4 bg-white shadow-sm border border-gray-200 rounded-lg cursor-grab hover:shadow-md hover:border-indigo-300 transition-all active:cursor-grabbing">
                        <div class="flex justify-between items-start mb-2">
                            <span class="px-2 py-1 text-[10px] font-bold uppercase tracking-wider rounded bg-indigo-50 text-indigo-600 border border-indigo-100">
                                Routine
                            </span>
                        </div>
                        <h4 class="text-base font-bold text-gray-900 leading-snug">{{ $task->template->title ?? 'Deleted Template' }}</h4>
                        @if($task->template && $task->template->description)
                            <p class="mt-2 text-xs text-gray-500 line-clamp-2">{{ $task->template->description }}</p>
                        @endif
                    </div>
                @endforeach
            </div>
        </div>
        @endforeach
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const columns = document.querySelectorAll('.kanban-column');
    
    columns.forEach(column => {
        new Sortable(column, {
            group: 'kanban', // set both lists to same group
            animation: 150,
            ghostClass: 'opacity-40',
            dragClass: 'shadow-2xl',
            easing: "cubic-bezier(1, 0, 0, 1)",
            onEnd: function (evt) {
                updateTaskCounters();
                saveAllColumns();
            }
        });
    });

    function updateTaskCounters() {
        ['todo', 'doing', 'done', 'tomorrow'].forEach(status => {
            const group = document.querySelector(`.kanban-column[data-status="${status}"]`);
            if (group) {
                const count = group.children.length;
                const counter = document.querySelector(`.task-count-${status}`);
                if (counter) counter.textContent = count;
            }
        });
    }

    function saveAllColumns() {
        let tasks = [];
        document.querySelectorAll('.kanban-column').forEach(column => {
            const status = column.getAttribute('data-status');
            column.querySelectorAll('.kanban-task').forEach((el, index) => {
                tasks.push({
                    id: el.getAttribute('data-id'),
                    order: index,
                    status: status
                });
            });
        });

        if (tasks.length === 0) return;

        fetch('{{ route("tasks.reorder") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'Accept': 'application/json'
            },
            body: JSON.stringify({ tasks: tasks })
        }).then(res => res.json())
          .catch(err => console.error('Failed to update task order:', err));
    }
});
</script>
@endpush
