/* ═══════════════════════════════════════════════════════════════
   Kanban Drag & Drop (native HTML5 API – no external library)
═══════════════════════════════════════════════════════════════ */

function initKanban(statusIds) {
    let draggedCard  = null;
    let sourceColumn = null;
    let sourceNextSibling = null;
    let dragPlaceholder = null;

    function createPlaceholder() {
        const ph = document.createElement('div');
        ph.className = 'kanban-placeholder';
        ph.style.cssText = 'height:80px;border:2px dashed var(--color-primary);border-radius:6px;background:color-mix(in srgb, var(--color-primary) 6%, transparent);opacity:.6;';
        return ph;
    }

    function getDropPosition(column, clientY) {
        const cards = [...column.querySelectorAll('.kanban-card:not(.dragging)')];
        for (const card of cards) {
            const { top, height } = card.getBoundingClientRect();
            if (clientY < top + height / 2) return card;
        }
        return null;
    }

    function initCard(card) {
        card.setAttribute('draggable', 'true');

        card.addEventListener('dragstart', (e) => {
            draggedCard = card;
            sourceColumn = card.closest('.kanban-column-body');
            sourceNextSibling = card.nextElementSibling;
            card.classList.add('dragging');
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/plain', card.dataset.taskId);

            dragPlaceholder = createPlaceholder();
            setTimeout(() => {
                card.style.opacity = '0.4';
            }, 0);
        });

        card.addEventListener('dragend', () => {
            card.classList.remove('dragging');
            card.style.opacity = '';
            dragPlaceholder?.remove();
            dragPlaceholder = null;
            draggedCard  = null;
            sourceColumn = null;
            sourceNextSibling = null;

            document.querySelectorAll('.kanban-column-body').forEach(col => {
                col.classList.remove('drag-over');
            });
        });
    }

    function initColumn(colBody) {
        colBody.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';

            if (!draggedCard) return;

            colBody.classList.add('drag-over');

            const before = getDropPosition(colBody, e.clientY);
            if (before) {
                colBody.insertBefore(dragPlaceholder, before);
            } else {
                colBody.appendChild(dragPlaceholder);
            }
        });

        colBody.addEventListener('dragleave', (e) => {
            if (!colBody.contains(e.relatedTarget)) {
                colBody.classList.remove('drag-over');
            }
        });

        colBody.addEventListener('drop', async (e) => {
            e.preventDefault();
            colBody.classList.remove('drag-over');

            if (!draggedCard) return;

            const newStatusId = parseInt(colBody.dataset.statusId);
            const taskId      = parseInt(draggedCard.dataset.taskId);
            const oldStatusId = parseInt(draggedCard.dataset.statusId);

            // Insert card at placeholder position
            dragPlaceholder?.replaceWith(draggedCard);
            draggedCard.dataset.statusId = newStatusId;

            // Update counter badges
            updateColumnCounters();

            // Update empty state
            updateEmptyStates();

            // Persist via API
            const cards = [...colBody.querySelectorAll('.kanban-card')];
            const position = cards.indexOf(draggedCard);
            const base = typeof BASE_URL !== 'undefined' ? BASE_URL : '';

            try {
                const res = await fetch(base + '/api/task/update-position', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        task_id:    taskId,
                        status_id:  newStatusId,
                        position:   position,
                        csrf_token: typeof CSRF_TOKEN !== 'undefined' ? CSRF_TOKEN : ''
                    })
                });
                if (!res.ok) throw new Error('API error');
            } catch (err) {
                console.error('Failed to update task position:', err);
                // Revert: move card back to its original position, not the end
                if (sourceColumn) sourceColumn.insertBefore(draggedCard, sourceNextSibling);
                draggedCard.dataset.statusId = oldStatusId;
                updateColumnCounters();
            }
        });
    }

    function updateColumnCounters() {
        document.querySelectorAll('.kanban-column').forEach(col => {
            const body  = col.querySelector('.kanban-column-body');
            const badge = col.querySelector('.kanban-count');
            if (badge && body) {
                badge.textContent = body.querySelectorAll('.kanban-card').length;
            }
        });
    }

    function updateEmptyStates() {
        document.querySelectorAll('.kanban-column-body').forEach(colBody => {
            let empty = colBody.querySelector('.kanban-empty');
            const hasCards = colBody.querySelectorAll('.kanban-card').length > 0;
            if (hasCards) {
                empty?.remove();
            } else if (!empty) {
                empty = document.createElement('div');
                empty.className = 'kanban-empty';
                empty.textContent = typeof APP_LANG !== 'undefined' && APP_LANG === 'en' ? 'Drag here' : 'Hierher ziehen';
                colBody.appendChild(empty);
            }
        });
    }

    // Initialize all cards and columns
    document.querySelectorAll('.kanban-card').forEach(initCard);
    document.querySelectorAll('.kanban-column-body').forEach(initColumn);

    // Observe for dynamically added cards (e.g., after AJAX)
    const observer = new MutationObserver(mutations => {
        mutations.forEach(mut => {
            mut.addedNodes.forEach(node => {
                if (node.nodeType === 1 && node.classList.contains('kanban-card')) {
                    initCard(node);
                }
            });
        });
    });
    document.querySelectorAll('.kanban-column-body').forEach(col => {
        observer.observe(col, { childList: true });
    });
}
