/**
 * Dashboard Kanban — drag tasks between columns + multi-select bulk moves.
 */
(function ($) {
    'use strict';

    var dragTaskId = 0;
    var dragFromCol = '';
    var selected = {};

    function ajaxUrl() {
        if (typeof newsai_vars !== 'undefined' && newsai_vars.ajax_url) {
            return newsai_vars.ajax_url;
        }
        return typeof window.ajaxurl === 'string' ? window.ajaxurl : '';
    }

    function nonce() {
        return typeof newsai_vars !== 'undefined' ? newsai_vars.nonce : '';
    }

    function clearDropHints() {
        $('.nros-kanban-body').removeClass('is-drag-over');
        $('.nros-kanban-card').removeClass('is-dragging');
    }

    function moveCardDom($card, targetCol) {
        var $body = $('.nros-kanban-body[data-kanban-drop="' + targetCol + '"]');
        if (!$body.length) {
            return;
        }
        $card.attr('data-kanban-col', targetCol);
        $body.append($card);
    }

    function selectedIds() {
        return Object.keys(selected)
            .map(function (k) { return parseInt(k, 10); })
            .filter(function (n) { return n > 0; });
    }

    function updateBulkBar() {
        var $bar = $('#nros-kanban-bulkbar');
        if (!$bar.length) {
            return;
        }
        var ids = selectedIds();
        if (!ids.length) {
            $bar.attr('hidden', 'hidden');
            return;
        }
        $bar.removeAttr('hidden');
        var tpl = $bar.attr('data-selected-template') || '%d';
        $('#nros-kanban-bulk-count').text(tpl.replace('%d', ids.length));
    }

    function clearSelection() {
        selected = {};
        $('.nros-kanban-check').prop('checked', false);
        $('.nros-kanban-card').removeClass('is-selected');
        updateBulkBar();
    }

    function selectAll() {
        $('.nros-kanban-check').each(function () {
            this.checked = true;
            var id = parseInt($(this).attr('data-task-id'), 10) || 0;
            if (id) {
                selected[id] = true;
            }
            $(this).closest('.nros-kanban-card').addClass('is-selected');
        });
        updateBulkBar();
    }

    function bulkMove(ids, targetCol, done) {
        ids = (ids || []).filter(function (n) { return n > 0; });
        targetCol = String(targetCol || '');
        if (!ids.length || !targetCol) {
            if (typeof done === 'function') { done({ moved: [], failed: [] }); }
            return;
        }
        $.post(ajaxUrl(), {
            action: 'newsai_kanban_bulk_move',
            nonce: nonce(),
            task_ids: ids,
            column: targetCol
        }).done(function (resp) {
            var data = (resp && resp.data) ? resp.data : { moved: [], failed: [] };
            (data.moved || []).forEach(function (tid) {
                var $card = $('.nros-kanban-card[data-task-id="' + tid + '"]');
                if ($card.length) {
                    moveCardDom($card, targetCol);
                }
                delete selected[tid];
            });
            $('.nros-kanban-check').prop('checked', false);
            $('.nros-kanban-card').removeClass('is-selected');
            updateBulkBar();
            if (typeof done === 'function') { done(data); }
        }).fail(function () {
            if (typeof done === 'function') { done(null); }
        });
    }

    function markAllDone() {
        var ids = [];
        $('.nros-kanban-card').each(function () {
            if (String($(this).attr('data-kanban-col') || '') !== 'done') {
                var tid = parseInt($(this).attr('data-task-id'), 10) || 0;
                if (tid) {
                    ids.push(tid);
                }
            }
        });
        bulkMove(ids, 'done');
    }

    function bindKanban() {
        var $board = $('#nros-kanban-view');
        if (!$board.length) {
            return;
        }

        $board.on('dragstart', '.nros-kanban-card', function (e) {
            var $card = $(this);
            dragTaskId = parseInt($card.attr('data-task-id'), 10) || 0;
            dragFromCol = String($card.attr('data-kanban-col') || '');
            $card.addClass('is-dragging');
            if (e.originalEvent && e.originalEvent.dataTransfer) {
                e.originalEvent.dataTransfer.effectAllowed = 'move';
                e.originalEvent.dataTransfer.setData('text/plain', String(dragTaskId));
            }
        });

        $board.on('dragend', '.nros-kanban-card', function () {
            clearDropHints();
            dragTaskId = 0;
            dragFromCol = '';
        });

        $board.on('dragover', '.nros-kanban-body', function (e) {
            e.preventDefault();
            $(this).addClass('is-drag-over');
        });

        $board.on('dragleave', '.nros-kanban-body', function () {
            $(this).removeClass('is-drag-over');
        });

        $board.on('drop', '.nros-kanban-body', function (e) {
            e.preventDefault();
            var $drop = $(this);
            var targetCol = String($drop.attr('data-kanban-drop') || '');
            clearDropHints();
            if (!dragTaskId || !targetCol || targetCol === dragFromCol) {
                return;
            }
            var $card = $('.nros-kanban-card[data-task-id="' + dragTaskId + '"]');
            if (!$card.length) {
                return;
            }
            moveCardDom($card, targetCol);
            $.post(ajaxUrl(), {
                action: 'newsai_kanban_move_task',
                nonce: nonce(),
                task_id: dragTaskId,
                column: targetCol
            }).fail(function () {
                moveCardDom($card, dragFromCol);
            });
        });

        // Don't let the checkbox initiate a card drag.
        $board.on('mousedown', '.nros-kanban-card__select', function (e) {
            e.stopPropagation();
        });

        $board.on('change', '.nros-kanban-check', function () {
            var id = parseInt($(this).attr('data-task-id'), 10) || 0;
            if (!id) {
                return;
            }
            var $card = $(this).closest('.nros-kanban-card');
            if (this.checked) {
                selected[id] = true;
                $card.addClass('is-selected');
            } else {
                delete selected[id];
                $card.removeClass('is-selected');
            }
            updateBulkBar();
        });

        $board.on('click', '#nros-kanban-bulk-apply', function () {
            bulkMove(selectedIds(), String($('#nros-kanban-bulk-col').val() || ''));
        });

        $board.on('click', '#nros-kanban-bulk-clear', function () {
            clearSelection();
        });
    }

    $(function () {
        bindKanban();
    });

    window.nrosKanban = {
        markAllDone: markAllDone,
        bulkMove: bulkMove,
        selectAll: selectAll,
        clearSelection: clearSelection
    };
}(jQuery));
