/**
 * JCOGS Image Pro - Color Picker Enhancement
 * ==========================================
 * Adds HTML5 color picker helper to color input fields
 * 
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2025 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.0
 * @link       https://JCOGS.net/
 * @since      Issue #61 - Color Picker Enhancement
 */

(function() {
    'use strict';
    
    /**
     * Initialize color picker for fields marked with data-color-picker attribute
     */
    function initColorPickers() {
        const colorFields = document.querySelectorAll('[data-color-picker="true"]');
        
        colorFields.forEach(function(field) {
            // Skip if already processed
            if (field.classList.contains('jcogs-color-picker-processed')) {
                return;
            }
            
            // Mark as processed
            field.classList.add('jcogs-color-picker-processed');
            
            // Wrap the field for better layout
            const wrapper = document.createElement('div');
            wrapper.className = 'jcogs-color-field-wrapper';
            field.parentNode.insertBefore(wrapper, field);
            wrapper.appendChild(field);
            
            // Create color picker button
            const pickerBtn = document.createElement('div');
            pickerBtn.className = 'jcogs-color-picker-btn';
            pickerBtn.title = 'Pick a color';
            
            // Create hidden HTML5 color input
            const colorInput = document.createElement('input');
            colorInput.type = 'color';
            colorInput.value = getInitialColorValue(field.value);
            
            // Create color preview div
            const colorPreview = document.createElement('div');
            colorPreview.className = 'jcogs-color-preview';
            colorPreview.style.backgroundColor = colorInput.value;
            
            pickerBtn.appendChild(colorInput);
            pickerBtn.appendChild(colorPreview);
            wrapper.appendChild(pickerBtn);
            
            // Sync color picker with text field
            colorInput.addEventListener('input', function() {
                field.value = colorInput.value.substring(1); // Remove # prefix
                colorPreview.style.backgroundColor = colorInput.value;
            });
            
            // Sync text field with color picker (when user types)
            field.addEventListener('input', function() {
                const normalizedColor = normalizeColorForPicker(field.value);
                if (normalizedColor) {
                    colorInput.value = normalizedColor;
                    colorPreview.style.backgroundColor = normalizedColor;
                }
            });
            
            // Update preview on blur to handle named colors and other formats
            field.addEventListener('blur', function() {
                const normalizedColor = normalizeColorForPicker(field.value);
                if (normalizedColor) {
                    colorPreview.style.backgroundColor = normalizedColor;
                }
            });
        });
    }
    
    /**
     * Get initial color value for the HTML5 color picker
     * Converts various color formats to #RRGGBB
     * 
     * @param {string} value Current field value
     * @returns {string} Normalized hex color with # prefix
     */
    function getInitialColorValue(value) {
        if (!value) {
            return '#000000';
        }
        
        const normalized = normalizeColorForPicker(value);
        return normalized || '#000000';
    }
    
    /**
     * Normalize color value to #RRGGBB format for HTML5 color picker
     * 
     * @param {string} colorValue Color in various formats
     * @returns {string|null} Normalized hex color or null if invalid
     */
    function normalizeColorForPicker(colorValue) {
        if (!colorValue || typeof colorValue !== 'string') {
            return null;
        }
        
        colorValue = colorValue.trim();
        
        // Remove # if present
        if (colorValue.startsWith('#')) {
            colorValue = colorValue.substring(1);
        }
        
        // Handle 6-digit hex
        if (/^[0-9A-Fa-f]{6}$/.test(colorValue)) {
            return '#' + colorValue.toUpperCase();
        }
        
        // Handle 3-digit hex (expand to 6 digits)
        if (/^[0-9A-Fa-f]{3}$/.test(colorValue)) {
            return '#' + colorValue[0] + colorValue[0] + 
                   colorValue[1] + colorValue[1] + 
                   colorValue[2] + colorValue[2];
        }
        
        // Handle 8-digit hex (RRGGBBAA - ignore alpha for HTML5 picker)
        if (/^[0-9A-Fa-f]{8}$/.test(colorValue)) {
            return '#' + colorValue.substring(0, 6).toUpperCase();
        }
        
        // Handle 4-digit hex (RGBA - expand and ignore alpha)
        if (/^[0-9A-Fa-f]{4}$/.test(colorValue)) {
            return '#' + colorValue[0] + colorValue[0] + 
                   colorValue[1] + colorValue[1] + 
                   colorValue[2] + colorValue[2];
        }
        
        // Handle rgb/rgba format
        const rgbMatch = colorValue.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);
        if (rgbMatch) {
            const r = parseInt(rgbMatch[1]).toString(16).padStart(2, '0');
            const g = parseInt(rgbMatch[2]).toString(16).padStart(2, '0');
            const b = parseInt(rgbMatch[3]).toString(16).padStart(2, '0');
            return '#' + r + g + b;
        }
        
        // For named colors or other formats, try to get computed style from a temporary element
        try {
            const temp = document.createElement('div');
            temp.style.color = colorValue;
            document.body.appendChild(temp);
            const computed = window.getComputedStyle(temp).color;
            document.body.removeChild(temp);
            
            // Extract RGB values from computed style
            const computedMatch = computed.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
            if (computedMatch) {
                const r = parseInt(computedMatch[1]).toString(16).padStart(2, '0');
                const g = parseInt(computedMatch[2]).toString(16).padStart(2, '0');
                const b = parseInt(computedMatch[3]).toString(16).padStart(2, '0');
                return '#' + r + g + b;
            }
        } catch (e) {
            // Silently fail for invalid colors
        }
        
        return null;
    }
    
    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initColorPickers);
    } else {
        initColorPickers();
    }
    
    // Re-initialize when content is dynamically added (for AJAX-loaded forms)
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes.length > 0) {
                initColorPickers();
            }
        });
    });
    
    // Start observing the document for changes
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
    
})();
