{% extends "base.html" %}
{% from "components/ui.html" import page_header, breadcrumb_nav, button, filter_badge %}
{% from "components/multi_select.html" import multi_select %}

{% block title %}{{ _('Kanban') }} - {{ app_name }}{% endblock %}

{% block content %}
{% set breadcrumbs = [
    {'text': _('Kanban Board')}
] %}

{% set kanban_actions %}
<div class="flex items-end gap-3 flex-wrap">
    <a href="{{ url_for('tasks.create_task', project_id=project_id if project_id else none, next=request.full_path) }}" class="inline-flex items-center gap-2 bg-primary text-white text-sm px-3 py-2 rounded-lg hover:bg-primary/90 transition-colors shrink-0">
        <i class="fas fa-plus"></i> {{ _('Add task') }}
    </a>
    <form method="get" id="kanbanFilterForm" class="flex items-center gap-3 flex-wrap">
        <div class="min-w-[200px]">
            {{ multi_select(
                field_name='project_ids',
                label='Project',
                items=projects,
                selected_ids=project_ids,
                item_id_attr='id',
                item_label_attr='name',
                placeholder='All Projects',
                show_search=True,
                form_id='kanbanFilterForm'
            ) }}
        </div>
        <div class="min-w-[200px]">
            {{ multi_select(
                field_name='user_ids',
                label='Assigned To',
                items=users,
                selected_ids=user_ids,
                item_id_attr='id',
                item_label_attr='display_name',
                placeholder='All Users',
                show_search=True,
                form_id='kanbanFilterForm'
            ) }}
        </div>
    </form>
    {% if current_user.is_admin %}
    <a href="{{ url_for('kanban.list_columns') }}" class="inline-flex items-center gap-2 bg-primary text-white text-sm px-3 py-2 rounded-lg hover:bg-primary/90 transition-colors shrink-0">
        <i class="fas fa-sliders-h"></i> {{ _('Manage Columns') }}
    </a>
    {% endif %}
</div>
{% endset %}

{{ page_header(
    icon_class='fas fa-columns',
    title_text=_('Kanban Board'),
    subtitle_text=_('Drag tasks between columns to update their status'),
    breadcrumbs=breadcrumbs,
    actions_html=kanban_actions
) }}

<div class="bg-card-light dark:bg-card-dark rounded-lg shadow" role="application" aria-label="{{ _('Kanban board') }}">
    {% set kanban_return_url = request.full_path %}
    {% include 'projects/_kanban_tailwind.html' %}
</div>

{% endblock %}

{% block scripts_extra %}
<script>
document.addEventListener('DOMContentLoaded', function () {
    const board = document.getElementById('kanbanBoard');
    if (!board) return;

    let dragCard = null;
    board.addEventListener('dragstart', (e) => {
        const card = e.target.closest('.kanban-card');
        if (card) {
            dragCard = card;
            card.classList.add('opacity-50');
            card.setAttribute('aria-grabbed', 'true');
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/plain', card.dataset.taskId);
        }
    });
    board.addEventListener('dragend', () => {
        if (dragCard) {
            dragCard.classList.remove('opacity-50');
            dragCard.setAttribute('aria-grabbed', 'false');
        }
        dragCard = null;
        document.querySelectorAll('.kanban-column-body').forEach(b => b.classList.remove('bg-blue-100','dark:bg-blue-900'));
    });
    document.querySelectorAll('.kanban-column-body').forEach(body => {
        body.addEventListener('dragover', (e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; body.classList.add('bg-blue-100','dark:bg-blue-900'); body.setAttribute('aria-dropeffect', 'move'); });
        body.addEventListener('dragleave', () => { body.classList.remove('bg-blue-100','dark:bg-blue-900'); body.removeAttribute('aria-dropeffect'); });
        body.addEventListener('drop', async (e) => {
            e.preventDefault(); body.classList.remove('bg-blue-100','dark:bg-blue-900');
            body.removeAttribute('aria-dropeffect');
            const targetStatus = body.dataset.status;
            const taskId = e.dataTransfer.getData('text/plain');
            const card = dragCard || board.querySelector(`[data-task-id="${taskId}"]`);
            if (card && card.dataset.status !== targetStatus) {
                const originalParent = card.parentElement;
                // Hide target empty placeholder before inserting
                const targetEmpty = body.querySelector('.kanban-empty');
                if (targetEmpty) targetEmpty.style.display = 'none';
                body.appendChild(card);
                try {
                    const res = await fetch(`/api/tasks/${taskId}/status`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token() }}', 'X-Requested-With': 'XMLHttpRequest' }, credentials: 'same-origin', body: JSON.stringify({ status: targetStatus }) });
                    if (!res.ok) throw new Error('Failed'); card.dataset.status = targetStatus;
                    updateColumnCounts();
                    toggleEmptyStatesForBodies([body, originalParent]);
                    announce(`${card.querySelector('h4, .kanban-card-title')?.textContent || 'Task'} {{ _('moved to') }} ${targetStatus}`);
                } catch (err) {
                    // Revert DOM move and empty states
                    originalParent.appendChild(card);
                    toggleEmptyStatesForBodies([body, originalParent]);
                }
            }
        });
    });

    // Inline status dropdown removed: status is determined by column.

    function updateColumnCounts(){
        document.querySelectorAll('.kanban-count').forEach(span => {
            const status = span.getAttribute('data-status');
            const count = document.querySelectorAll(`.kanban-card[data-status="${status}"]`).length;
            span.textContent = count;
        });
        // Also toggle empty placeholders after any count recalculation
        document.querySelectorAll('.kanban-column-body').forEach(body => toggleEmptyStateForBody(body));
    }

    function toggleEmptyStatesForBodies(bodies){
        if (!Array.isArray(bodies)) return;
        bodies.forEach(b => { if (b) toggleEmptyStateForBody(b); });
    }

    function toggleEmptyStateForBody(body){
        const cards = body.querySelectorAll('.kanban-card');
        let empty = body.querySelector('.kanban-empty');
        if (cards.length === 0) {
            if (!empty) {
                empty = document.createElement('div');
                empty.className = 'kanban-empty text-center text-text-muted-light dark:text-text-muted-dark py-10';
                empty.innerHTML = '<p>{{ _('No tasks in this column.') }}</p>';
                body.appendChild(empty);
            }
            empty.style.display = '';
        } else if (empty) {
            empty.style.display = 'none';
        }
    }

    // Simple aria-live region for announcements
    function announce(message){
        try {
            let live = document.getElementById('kanban-live-region');
            if (!live) {
                live = document.createElement('div');
                live.id = 'kanban-live-region';
                live.setAttribute('aria-live', 'polite');
                live.setAttribute('aria-atomic', 'true');
                live.className = 'sr-only';
                document.body.appendChild(live);
            }
            live.textContent = message;
        } catch(_) {}
    }
});
</script>
{% endblock %}


