/**
 * Print functionality for Hangit plugin using HTML2Canvas
 */

// Helper function to convert hex color to RGB
function hexToRgb(hex) {
    // Remove the # if present
    hex = hex.replace(/^#/, '');
    
    // Parse the hex values
    let r, g, b;
    if (hex.length === 3) {
        // For shorthand like #ABC
        r = parseInt(hex.charAt(0) + hex.charAt(0), 16);
        g = parseInt(hex.charAt(1) + hex.charAt(1), 16);
        b = parseInt(hex.charAt(2) + hex.charAt(2), 16);
    } else if (hex.length === 6) {
        // For full hex like #AABBCC
        r = parseInt(hex.substring(0, 2), 16);
        g = parseInt(hex.substring(2, 4), 16);
        b = parseInt(hex.substring(4, 6), 16);
    } else {
        return null; // Invalid hex color
    }
    
    return { r, g, b };
}

document.addEventListener('DOMContentLoaded', function() {
    // Get the print button
    const printButton = document.getElementById('hangit-print');
    
    if (printButton) {
        // Add click event listener to the print button
        printButton.addEventListener('click', function() {
            // Disable the button and change text to indicate processing
            printButton.disabled = true;
            const originalText = printButton.textContent;
            printButton.textContent = 'Processing...';
            // Get the showroom element that contains both background and foreground
            const showroom = document.getElementById('the-showroom');
            
            if (showroom && typeof html2canvas === 'function') {
                // Create a loading indicator with spinner
                const loadingIndicator = document.createElement('div');
                loadingIndicator.style.position = 'fixed';
                loadingIndicator.style.top = '50%';
                loadingIndicator.style.left = '50%';
                loadingIndicator.style.transform = 'translate(-50%, -50%)';
                loadingIndicator.style.background = 'rgba(255, 255, 255, 0.9)';
                loadingIndicator.style.padding = '20px';
                loadingIndicator.style.borderRadius = '5px';
                loadingIndicator.style.zIndex = '9999';
                loadingIndicator.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.3)';
                loadingIndicator.style.display = 'flex';
                loadingIndicator.style.flexDirection = 'column';
                loadingIndicator.style.alignItems = 'center';
                loadingIndicator.style.justifyContent = 'center';
                
                // Create spinner element
                const spinner = document.createElement('div');
                spinner.style.border = '5px solid #f3f3f3';
                spinner.style.borderTop = '5px solid #3498db';
                spinner.style.borderRadius = '50%';
                spinner.style.width = '40px';
                spinner.style.height = '40px';
                spinner.style.animation = 'hangitSpin 1s linear infinite';
                spinner.style.marginBottom = '10px';
                
                // Add keyframes for spinner animation
                if (!document.getElementById('hangitSpinKeyframes')) {
                    const styleSheet = document.createElement('style');
                    styleSheet.id = 'hangitSpinKeyframes';
                    styleSheet.textContent = `
                        @keyframes hangitSpin {
                            0% { transform: rotate(0deg); }
                            100% { transform: rotate(360deg); }
                        }
                    `;
                    document.head.appendChild(styleSheet);
                }
                
                // Create text element
                const loadingText = document.createElement('div');
                loadingText.textContent = 'Preparing print preview...';
                loadingText.style.marginTop = '10px';
                loadingText.style.fontWeight = 'bold';
                
                // Add elements to loading indicator
                loadingIndicator.appendChild(spinner);
                loadingIndicator.appendChild(loadingText);
                document.body.appendChild(loadingIndicator);
                
                // Use html2canvas to create an image of the showroom
                html2canvas(showroom, {
                    allowTaint: true,
                    useCORS: true,
                    logging: false,
                    scale: 2, // Higher quality
                    backgroundColor: null,
                    onclone: function(clonedDoc) {
                        // Make sure the frame is visible in the cloned document
                        const clonedFrame = clonedDoc.getElementById('theframe');
                        const clonedHanging = clonedDoc.getElementById('thehanging');
                        
                        // Get the current border settings
                        const originalFrame = document.getElementById('theframe');
                        const borderWidth = document.getElementById('hangit-border-width').value;
                        const borderColor = document.getElementById('hangit-border-color').value;
                        
                        if (clonedFrame) {
                            // Apply visibility settings
                            clonedFrame.style.visibility = 'visible';
                            clonedFrame.style.display = 'block';
                            clonedFrame.style.opacity = '1';
                            
                            // Apply border settings with 3D effect for larger borders
                            if (borderWidth === '0') {
                                clonedFrame.style.border = 'none';
                                clonedFrame.style.backgroundColor = 'transparent';
                                clonedFrame.style.boxShadow = 'none';
                            } else if (parseInt(borderWidth) <= 2) {
                                // Simple border for thin frames
                                clonedFrame.style.border = borderWidth + 'px solid ' + borderColor;
                                clonedFrame.style.backgroundColor = borderColor;
                                clonedFrame.style.boxShadow = 'none';
                            } else {
                                // Simple border for thicker frames
                                clonedFrame.style.border = borderWidth + 'px solid ' + borderColor;
                                clonedFrame.style.backgroundColor = borderColor;
                                clonedFrame.style.boxShadow = 'none';
                            }
                            
                            // Ensure proper aspect ratio
                            clonedFrame.style.objectFit = 'contain';
                        }
                        
                        if (clonedHanging) {
                            clonedHanging.style.visibility = 'visible';
                            clonedHanging.style.display = 'block';
                            clonedHanging.style.opacity = '1';
                        }
                    }
                }).then(function(canvas) {
                    // Remove loading indicator
                    document.body.removeChild(loadingIndicator);
                    
                    // Create a print window - use a single named window to prevent multiple tabs
                    const printWindow = window.open('', 'hangit_print_preview');
                    
                    // Re-enable the print button and restore text immediately after opening window
                    // This ensures the button resets even if the popup blocks further execution
                    printButton.disabled = false;
                    printButton.textContent = originalText;
                    
                    if (!printWindow) {
                        alert('Please allow popups for this website to print');
                        return;
                    }
                    
                    // Convert canvas to an image
                    const img = canvas.toDataURL('image/png');
                    
                    // Write HTML to the print window
                    printWindow.document.write(`
                        <!DOCTYPE html>
                        <html>
                        <head>
                            <title>Print Preview</title>
                            <style>
                                body {
                                    margin: 0;
                                    padding: 0;
                                    display: flex;
                                    justify-content: center;
                                    align-items: center;
                                    height: 100vh;
                                }
                                img {
                                    max-width: 100%;
                                    max-height: 100vh;
                                    object-fit: contain;
                                }
                                .print-container {
                                    text-align: center;
                                }
                                .print-button {
                                    margin-top: 20px;
                                    padding: 10px 20px;
                                    background-color: #0073aa;
                                    color: white;
                                    border: none;
                                    border-radius: 4px;
                                    cursor: pointer;
                                    font-size: 16px;
                                }
                                .print-button:hover {
                                    background-color: #005177;
                                }
                                @media print {
                                    .print-button {
                                        display: none;
                                    }
                                }
                            </style>
                        </head>
                        <body>
                            <div class="print-container">
                                <img src="${img}" alt="Room Preview" />
                                <div>
                                    <button class="print-button" onclick="window.print(); window.close(); return false;">Print</button>
                                </div>
                            </div>
                        </body>
                        </html>
                    `);
                    
                    // Finish writing and focus the window
                    printWindow.document.close();
                    printWindow.focus();
                }).catch(function(error) {
                    // Log the error
                    console.error('Error generating print preview:', error);
                    
                    // Remove loading indicator if it exists
                    if (document.body.contains(loadingIndicator)) {
                        document.body.removeChild(loadingIndicator);
                    }
                    
                    // Re-enable the print button and restore text
                    printButton.disabled = false;
                    printButton.textContent = originalText;
                    
                    // Show error message to user
                    alert('Sorry, there was an error generating the print preview. Please try again.');
                });
            } else {
                // Fallback to regular print if html2canvas is not available
                alert('Print preview is not available. Using standard print function instead.');
                window.print();
                
                // Make sure to reset the button
                printButton.disabled = false;
                printButton.textContent = originalText;
            }
        });
    }
});
