/**
 * Kanban Drag-and-Drop Pipeline Manager
 */
const Kanban = {
    draggedDealId: null,

    onDragStart(e, dealId) {
        this.draggedDealId = dealId;
        e.dataTransfer.setData('text/plain', dealId);
        e.target.style.opacity = '0.4';
    },

    onDragOver(e) {
        e.preventDefault();
        const col = e.currentTarget;
        col.classList.add('bg-slate-800/40', 'border-emerald-500/30');
    },

    onDragLeave(e) {
        const col = e.currentTarget;
        col.classList.remove('bg-slate-800/40', 'border-emerald-500/30');
    },

    async onDrop(e, targetStageId) {
        e.preventDefault();
        const col = e.currentTarget;
        col.classList.remove('bg-slate-800/40', 'border-emerald-500/30');

        const dealId = this.draggedDealId;
        const dealEl = document.getElementById(`deal-card-${dealId}`);
        if (dealEl) {
            dealEl.style.opacity = '1';
            col.appendChild(dealEl);
        }

        try {
            const formData = new FormData();
            formData.append('deal_id', dealId);
            formData.append('stage_id', targetStageId);

            const res = await fetch('/api/deals/move', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await res.json();

            if (data.success) {
                App.toast('Deal moved successfully!', 'success');
            } else {
                App.toast(data.error || 'Failed to move deal', 'error');
            }
        } catch (err) {
            App.toast('Error connecting to server', 'error');
        }
    },

    openCreateModal() {
        document.getElementById('kanban-create-deal-modal').classList.remove('hidden');
    },

    closeCreateModal() {
        document.getElementById('kanban-create-deal-modal').classList.add('hidden');
    },

    async submitDeal(e) {
        e.preventDefault();
        const formData = new FormData(e.target);

        try {
            const res = await fetch('/api/deals/create', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await res.json();

            if (data.success) {
                App.toast('Deal created successfully!', 'success');
                window.location.reload();
            } else {
                App.toast(data.error || 'Failed to create deal', 'error');
            }
        } catch (err) {
            App.toast('Error saving deal', 'error');
        }
    }
};
