// JavaScript drag-and-drop implementation for MAUI Blazor Hybrid
window.dragDropManager = {
    draggedElement: null,
    draggedCardId: null,
    startX: 0,
    startY: 0,
    isDragging: false,
    dragThreshold: 5,
    dropZones: [],
    currentDropZone: null,
    dragPreview: null,
    blazorReference: null,

    // Initialize drag-and-drop for a card element
    initializeCard: function (cardElement, cardId, blazorRef) {
        this.blazorReference = blazorRef;
        
        // Remove existing event listeners to prevent duplicates
        this.removeCardListeners(cardElement);
        
        // Add mouse events
        cardElement.addEventListener('mousedown', (e) => this.onMouseDown(e, cardElement, cardId));
        
        // Add touch events for mobile
        cardElement.addEventListener('touchstart', (e) => this.onTouchStart(e, cardElement, cardId), { passive: false });
        
        // Prevent default drag behavior
        cardElement.draggable = false;
        cardElement.style.userSelect = 'none';
        cardElement.style.webkitUserSelect = 'none';
        cardElement.style.cursor = 'grab';
    },

    // Remove event listeners from a card
    removeCardListeners: function (cardElement) {
        cardElement.removeEventListener('mousedown', this.onMouseDown);
        cardElement.removeEventListener('touchstart', this.onTouchStart);
    },

    // Initialize drop zone
    initializeDropZone: function (dropZoneElement, column, position) {
        dropZoneElement.dataset.column = column;
        dropZoneElement.dataset.position = position;
        this.dropZones.push({
            element: dropZoneElement,
            column: column,
            position: position
        });
    },

    // Mouse down event
    onMouseDown: function (e, cardElement, cardId) {
        if (e.button !== 0) return; // Only left mouse button
        
        this.startDrag(e.clientX, e.clientY, cardElement, cardId);
        
        // Add global mouse event listeners
        document.addEventListener('mousemove', this.onMouseMove.bind(this));
        document.addEventListener('mouseup', this.onMouseUp.bind(this));
        
        e.preventDefault();
    },

    // Touch start event
    onTouchStart: function (e, cardElement, cardId) {
        if (e.touches.length !== 1) return;
        
        const touch = e.touches[0];
        this.startDrag(touch.clientX, touch.clientY, cardElement, cardId);
        
        // Add global touch event listeners
        document.addEventListener('touchmove', this.onTouchMove.bind(this), { passive: false });
        document.addEventListener('touchend', this.onTouchEnd.bind(this));
        
        e.preventDefault();
    },

    // Start drag operation
    startDrag: function (clientX, clientY, cardElement, cardId) {
        this.startX = clientX;
        this.startY = clientY;
        this.draggedElement = cardElement;
        this.draggedCardId = cardId;
        this.isDragging = false; // Will be set to true when threshold is exceeded
        
        // Change cursor
        cardElement.style.cursor = 'grabbing';
    },

    // Mouse move event
    onMouseMove: function (e) {
        this.handleMove(e.clientX, e.clientY);
    },

    // Touch move event
    onTouchMove: function (e) {
        if (e.touches.length !== 1) return;
        const touch = e.touches[0];
        this.handleMove(touch.clientX, touch.clientY);
        e.preventDefault();
    },

    // Handle move (common for mouse and touch)
    handleMove: function (clientX, clientY) {
        if (!this.draggedElement) return;
        
        const deltaX = Math.abs(clientX - this.startX);
        const deltaY = Math.abs(clientY - this.startY);
        
        // Check if we've moved enough to start dragging
        if (!this.isDragging && (deltaX > this.dragThreshold || deltaY > this.dragThreshold)) {
            this.isDragging = true;
            this.startDragVisuals();
            
            // Notify Blazor that dragging started
            if (this.blazorReference) {
                this.blazorReference.invokeMethodAsync('OnDragStarted', this.draggedCardId);
            }
        }
        
        if (this.isDragging) {
            this.updateDragPreview(clientX, clientY);
            this.updateDropZoneHighlights(clientX, clientY);
        }
    },

    // Start drag visual effects
    startDragVisuals: function () {
        if (!this.draggedElement) return;
        
        // Add drag class to original element
        this.draggedElement.classList.add('dragging');
        this.draggedElement.style.opacity = '0.5';
        this.draggedElement.style.transform = 'scale(0.95)';
        
        // Create drag preview
        this.createDragPreview();
    },

    // Create drag preview element
    createDragPreview: function () {
        if (!this.draggedElement) return;
        
        // Clone the dragged element
        this.dragPreview = this.draggedElement.cloneNode(true);
        this.dragPreview.style.position = 'fixed';
        this.dragPreview.style.pointerEvents = 'none';
        this.dragPreview.style.zIndex = '9999';
        this.dragPreview.style.transform = 'rotate(5deg) scale(0.9)';
        this.dragPreview.style.opacity = '0.8';
        this.dragPreview.style.boxShadow = '0 15px 50px rgba(0, 0, 0, 0.5)';
        this.dragPreview.style.border = '2px solid #3b82f6';
        this.dragPreview.style.borderRadius = '8px';
        this.dragPreview.style.backgroundColor = 'white';
        
        document.body.appendChild(this.dragPreview);
    },

    // Update drag preview position
    updateDragPreview: function (clientX, clientY) {
        if (!this.dragPreview) return;
        
        this.dragPreview.style.left = (clientX - 50) + 'px';
        this.dragPreview.style.top = (clientY - 50) + 'px';
    },

    // Update drop zone highlights
    updateDropZoneHighlights: function (clientX, clientY) {
        const elementUnderCursor = document.elementFromPoint(clientX, clientY);
        let newDropZone = null;
        
        // Find if we're over a drop zone
        for (let dropZone of this.dropZones) {
            if (dropZone.element.contains(elementUnderCursor) || dropZone.element === elementUnderCursor) {
                newDropZone = dropZone;
                break;
            }
        }
        
        // Update drop zone highlights
        if (newDropZone !== this.currentDropZone) {
            // Remove highlight from previous drop zone
            if (this.currentDropZone) {
                this.currentDropZone.element.classList.remove('drop-zone-active');
                
                // Notify Blazor about drop zone leave
                if (this.blazorReference) {
                    this.blazorReference.invokeMethodAsync('OnDropZoneLeave');
                }
            }
            
            // Add highlight to new drop zone
            if (newDropZone) {
                newDropZone.element.classList.add('drop-zone-active');
                
                // Notify Blazor about drop zone enter
                if (this.blazorReference) {
                    this.blazorReference.invokeMethodAsync('OnDropZoneEnter', 
                        parseInt(newDropZone.column), parseInt(newDropZone.position));
                }
            }
            
            this.currentDropZone = newDropZone;
        }
    },

    // Mouse up event
    onMouseUp: function (e) {
        this.endDrag(e.clientX, e.clientY);
        
        // Remove global mouse event listeners
        document.removeEventListener('mousemove', this.onMouseMove.bind(this));
        document.removeEventListener('mouseup', this.onMouseUp.bind(this));
    },

    // Touch end event
    onTouchEnd: function (e) {
        if (e.changedTouches.length !== 1) return;
        
        const touch = e.changedTouches[0];
        this.endDrag(touch.clientX, touch.clientY);
        
        // Remove global touch event listeners
        document.removeEventListener('touchmove', this.onTouchMove.bind(this));
        document.removeEventListener('touchend', this.onTouchEnd.bind(this));
    },

    // End drag operation
    endDrag: function (clientX, clientY) {
        if (!this.draggedElement) return;
        
        // Reset cursor
        this.draggedElement.style.cursor = 'grab';
        
        if (this.isDragging) {
            // Handle drop
            if (this.currentDropZone && this.blazorReference) {
                this.blazorReference.invokeMethodAsync('OnCardDropped', 
                    this.draggedCardId, 
                    parseInt(this.currentDropZone.column), 
                    parseInt(this.currentDropZone.position));
            }
            
            // Clean up drag visuals
            this.endDragVisuals();
            
            // Notify Blazor that dragging ended
            if (this.blazorReference) {
                this.blazorReference.invokeMethodAsync('OnDragEnded');
            }
        }
        
        // Reset state
        this.resetDragState();
    },

    // End drag visual effects
    endDragVisuals: function () {
        if (this.draggedElement) {
            this.draggedElement.classList.remove('dragging');
            this.draggedElement.style.opacity = '';
            this.draggedElement.style.transform = '';
        }
        
        if (this.dragPreview) {
            document.body.removeChild(this.dragPreview);
            this.dragPreview = null;
        }
        
        // Remove all drop zone highlights
        this.dropZones.forEach(dropZone => {
            dropZone.element.classList.remove('drop-zone-active');
        });
    },

    // Reset drag state
    resetDragState: function () {
        this.draggedElement = null;
        this.draggedCardId = null;
        this.isDragging = false;
        this.currentDropZone = null;
        this.startX = 0;
        this.startY = 0;
    },

    // Clean up all drop zones (call when component is disposed)
    cleanup: function () {
        this.dropZones = [];
        this.resetDragState();
        if (this.dragPreview) {
            document.body.removeChild(this.dragPreview);
            this.dragPreview = null;
        }
    }
};
