/**
 * Frame border controls for Hangit plugin
 */

// 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 frame element
    const frame = document.getElementById('theframe');
    const borderWidthSlider = document.getElementById('hangit-border-width');
    const borderWidthValue = document.getElementById('hangit-border-width-value');
    const borderColorInput = document.getElementById('hangit-border-color');
    
    if (frame && borderWidthSlider && borderColorInput) {
        // Apply initial border settings
        applyBorderSettings();
        
        // Add event listeners for border controls
        borderWidthSlider.addEventListener('input', function() {
            // Update the displayed value
            if (borderWidthValue) {
                borderWidthValue.textContent = this.value;
            }
            applyBorderSettings();
        });
        
        borderColorInput.addEventListener('input', applyBorderSettings);
        
        // Function to apply border settings
        function applyBorderSettings() {
            const width = borderWidthSlider.value;
            const color = borderColorInput.value;
            
            if (width === '0') {
                frame.style.border = 'none';
                frame.style.backgroundColor = 'transparent';
                frame.style.boxShadow = 'none';
            } else if (parseInt(width) <= 2) {
                // Simple border for thin frames
                frame.style.border = width + 'px solid ' + color;
                frame.style.backgroundColor = color;
                frame.style.boxShadow = 'none';
            } else {
                // Simple border for thicker frames
                frame.style.border = width + 'px solid ' + color;
                frame.style.backgroundColor = color;
                frame.style.boxShadow = 'none';
            }
            
            // Ensure proper aspect ratio
            frame.style.objectFit = 'contain';
        }
    }
});
