/**
 * Vanilla JavaScript dragging implementation for Hangit plugin
 * No jQuery UI dependencies
 */

// Initialize dragging functionality when the DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    initDraggable();
    
    // Also initialize when Thickbox is opened
    const hangerLink = document.getElementById('hangerlink');
    if (hangerLink) {
        hangerLink.addEventListener('click', function() {
            // Wait for Thickbox content to load
            setTimeout(function() {
                initDraggable();
            }, 500);
        });
    }
});

/**
 * Initialize draggable functionality for the frame element
 */
function initDraggable() {
    const frame = document.getElementById('theframe');
    if (!frame) {
        console.log('Frame element not found');
        return;
    }
    
    console.log('Initializing vanilla drag');
    
    // Variables to track dragging and resizing state
    let isDragging = false;
    let isResizing = false;
    let startX, startY;
    let startLeft, startTop;
    let startWidth, startHeight;
    let aspectRatio = 1;
    
    // Add mouse event listeners with resize detection
    frame.addEventListener('mousedown', function(e) {
        // Check if click is in the bottom right 10% of the image (for resizing)
        const frameRect = frame.getBoundingClientRect();
        const rightEdgeZone = frameRect.width * 0.1;
        const bottomEdgeZone = frameRect.height * 0.1;
        
        if (e.clientX > frameRect.right - rightEdgeZone && 
            e.clientY > frameRect.bottom - bottomEdgeZone) {
            startResize(e);
        } else {
            startDrag(e);
        }
    });
    
    // Add touch event listeners for mobile with resize detection
    frame.addEventListener('touchstart', function(e) {
        const touch = e.touches[0];
        const frameRect = frame.getBoundingClientRect();
        const rightEdgeZone = frameRect.width * 0.1;
        const bottomEdgeZone = frameRect.height * 0.1;
        
        // Create a mouse event from the touch event
        const mouseEvent = new MouseEvent('mousedown', {
            clientX: touch.clientX,
            clientY: touch.clientY
        });
        
        // Check if touch is in the resize zone
        if (touch.clientX > frameRect.right - rightEdgeZone && 
            touch.clientY > frameRect.bottom - bottomEdgeZone) {
            startResize(mouseEvent);
        } else {
            startDrag(mouseEvent);
        }
    });
    
    /**
     * Start dragging the element
     */
    function startDrag(e) {
        if (isResizing) return;
        e.preventDefault();
        
        // Get initial positions
        startX = e.clientX;
        startY = e.clientY;
        
        // Get current element position
        const computedStyle = window.getComputedStyle(frame);
        startLeft = parseInt(computedStyle.left) || 0;
        startTop = parseInt(computedStyle.top) || 0;
        
        isDragging = true;
        
        // Add event listeners for drag and end
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', stopDrag);
        document.addEventListener('touchmove', handleTouchDrag);
        document.addEventListener('touchend', stopDrag);
        
        // Set cursor style
        frame.style.cursor = 'grabbing';
    }
    
    /**
     * Handle dragging movement
     */
    function drag(e) {
        if (!isDragging) return;
        
        // Calculate new position
        const dx = e.clientX - startX;
        const dy = e.clientY - startY;
        
        // Get parent container bounds
        const parent = frame.parentElement;
        const parentRect = parent.getBoundingClientRect();
        const frameRect = frame.getBoundingClientRect();
        
        // Calculate new position with boundary constraints
        let newLeft = startLeft + dx;
        let newTop = startTop + dy;
        
        // Apply boundary constraints
        if (newLeft < 0) newLeft = 0;
        if (newTop < 0) newTop = 0;
        if (newLeft + frameRect.width > parentRect.width) {
            newLeft = parentRect.width - frameRect.width;
        }
        if (newTop + frameRect.height > parentRect.height) {
            newTop = parentRect.height - frameRect.height;
        }
        
        // Apply new position
        frame.style.left = newLeft + 'px';
        frame.style.top = newTop + 'px';
    }
    
    /**
     * Start resizing the element
     */
    function startResize(e) {
        if (isDragging) return;
        e.preventDefault();
        
        // Get initial positions
        startX = e.clientX;
        startY = e.clientY;
        
        // Get current element dimensions and position
        const computedStyle = window.getComputedStyle(frame);
        startWidth = parseInt(computedStyle.width) || frame.offsetWidth;
        startHeight = parseInt(computedStyle.height) || frame.offsetHeight;
        startLeft = parseInt(computedStyle.left) || 0;
        
        // Calculate aspect ratio to maintain
        aspectRatio = startWidth / startHeight;
        
        isResizing = true;
        
        // Add event listeners for resize and end
        document.addEventListener('mousemove', resize);
        document.addEventListener('mouseup', stopResize);
        document.addEventListener('touchmove', handleTouchResize);
        document.addEventListener('touchend', stopResize);
        
        // Set cursor style
        document.body.style.cursor = 'nwse-resize';
    }
    
    /**
     * Handle resizing movement
     */
    function resize(e) {
        if (!isResizing) return;
        
        // Calculate new dimensions
        const dx = e.clientX - startX;
        let newWidth = startWidth + dx;
        
        // Get parent container bounds
        const parent = frame.parentElement;
        const parentRect = parent.getBoundingClientRect();
        
        // Apply minimum size constraint
        if (newWidth < 50) newWidth = 50;
        
        // Apply maximum size constraint (parent width)
        if (startLeft + newWidth > parentRect.width) {
            newWidth = parentRect.width - startLeft;
        }
        
        // Calculate height based on aspect ratio
        let newHeight = newWidth / aspectRatio;
        
        // Apply maximum height constraint
        if (newHeight > parentRect.height) {
            newHeight = parentRect.height;
            newWidth = newHeight * aspectRatio;
        }
        
        // Apply new dimensions
        frame.style.width = newWidth + 'px';
        frame.style.height = newHeight + 'px';
    }
    
    /**
     * Handle touch resizing
     */
    function handleTouchResize(e) {
        if (!isResizing) return;
        
        e.preventDefault(); // Prevent scrolling while resizing
        
        const touch = e.touches[0];
        const mouseEvent = new MouseEvent('mousemove', {
            clientX: touch.clientX,
            clientY: touch.clientY
        });
        
        resize(mouseEvent);
    }
    
    /**
     * Stop resizing
     */
    function stopResize() {
        if (!isResizing) return;
        
        isResizing = false;
        
        // Remove event listeners
        document.removeEventListener('mousemove', resize);
        document.removeEventListener('mouseup', stopResize);
        document.removeEventListener('touchmove', handleTouchResize);
        document.removeEventListener('touchend', stopResize);
        
        // Reset cursor style
        document.body.style.cursor = 'default';
    }
    
    /**
     * Handle touch dragging
     */
    function handleTouchDrag(e) {
        if (!isDragging) return;
        
        e.preventDefault(); // Prevent scrolling while dragging
        
        const touch = e.touches[0];
        const mouseEvent = new MouseEvent('mousemove', {
            clientX: touch.clientX,
            clientY: touch.clientY
        });
        
        drag(mouseEvent);
    }
    
    /**
     * Stop dragging
     */
    function stopDrag() {
        if (!isDragging) return;
        
        isDragging = false;
        
        // Remove event listeners
        document.removeEventListener('mousemove', drag);
        document.removeEventListener('mouseup', stopDrag);
        document.removeEventListener('touchmove', handleTouchDrag);
        document.removeEventListener('touchend', stopDrag);
        
        // Reset cursor style
        frame.style.cursor = 'move';
    }
    
    // Set initial position to center if not already positioned
    if (!frame.style.left || !frame.style.top) {
        const parent = frame.parentElement;
        const parentRect = parent.getBoundingClientRect();
        const frameRect = frame.getBoundingClientRect();
        
        const centerX = (parentRect.width - frameRect.width) / 2;
        const centerY = (parentRect.height - frameRect.height) / 2;
        
        frame.style.left = centerX + 'px';
        frame.style.top = centerY + 'px';
    }
    
    // Ensure the frame has proper styling
    frame.style.position = 'absolute';
    frame.style.cursor = 'move';
    
    // Add cursor change on hover over the resize area
    frame.addEventListener('mousemove', function(e) {
        const frameRect = frame.getBoundingClientRect();
        const rightEdgeZone = frameRect.width * 0.1;
        const bottomEdgeZone = frameRect.height * 0.1;
        
        if (e.clientX > frameRect.right - rightEdgeZone && 
            e.clientY > frameRect.bottom - bottomEdgeZone) {
            frame.style.cursor = 'nwse-resize';
        } else {
            frame.style.cursor = 'move';
        }
    });
    
    // Reset cursor when mouse leaves the frame
    frame.addEventListener('mouseleave', function() {
        if (!isDragging && !isResizing) {
            frame.style.cursor = 'move';
        }
    });
}
