/**
 * Font Awesome to Lucide Icon Translation Utility
 * Converts existing Font Awesome icons to Lucide icons dynamically
 * 
 * Usage:
 * - Include this script after Lucide is loaded
 * - Call window.translateFAToLucide() to convert all FA icons on the page
 * - Call it after dynamically adding new content with FA icons
 */

(function() {
    'use strict';
    
    // Font Awesome to Lucide icon mapping
    const iconMap = {
        'trophy': 'trophy',
        'calendar': 'calendar',
        'calendar-alt': 'calendar',
        'map-marker-alt': 'map-pin',
        'map-marker': 'map-pin',
        'fire': 'flame',
        'sync-alt': 'refresh-cw',
        'sync': 'refresh-cw',
        'external-link-alt': 'external-link',
        'external-link': 'external-link',
        'cogs': 'settings',
        'cog': 'settings',
        'wrench': 'wrench',
        'exclamation-triangle': 'alert-triangle',
        'redo': 'rotate-cw',
        'users': 'users',
        'users-slash': 'user-x',
        'user-slash': 'user-x',
        'user': 'user',
        'plus': 'plus',
        'clock': 'clock',
        'layer-group': 'layers',
        'list-check': 'list-checks',
        'list-ul': 'list',
        'list': 'list',
        'male': 'user',
        'female': 'user',
        'star': 'star',
        'running': 'activity',
        'file-alt': 'file-text',
        'file': 'file',
        'palette': 'palette',
        'tags': 'tags',
        'tag': 'tag',
        'mars': 'user',
        'venus': 'user',
        'venus-mars': 'users',
        'birthday-cake': 'cake',
        'id-card': 'id-card',
        'certificate': 'award',
        'robot': 'bot',
        'gavel': 'gavel',
        'weight-hanging': 'scale',
        'info-circle': 'info',
        'info': 'info',
        'table': 'table',
        'print': 'printer',
        'bolt': 'zap',
        'arrow-right': 'arrow-right',
        'ellipsis-h': 'more-horizontal',
        'play': 'play',
        'clipboard-list': 'clipboard-list',
        'clipboard': 'clipboard',
        'file-pdf': 'file-text',
        'code': 'code',
        'file-csv': 'file-spreadsheet',
        'eye': 'eye',
        'filter': 'filter',
        'shield-check': 'shield-check',
        'shield': 'shield',
        'sitemap': 'git-branch',
        'check-circle': 'check-circle',
        'check': 'check',
        'user-check': 'user-check',
        'ruler': 'ruler',
        'edit': 'edit',
        'door-open': 'door-open',
        'lock': 'lock',
        'unlock': 'unlock',
        'search': 'search',
        'download': 'download',
        'upload': 'upload',
        'save': 'save',
        'trash': 'trash-2',
        'trash-alt': 'trash-2',
        'home': 'home',
        'dashboard': 'layout-dashboard',
        'chart-bar': 'bar-chart',
        'chart-line': 'trending-up',
        'chart-pie': 'pie-chart',
        'caret-down': 'chevron-down',
        'caret-up': 'chevron-up',
        'caret-left': 'chevron-left',
        'caret-right': 'chevron-right',
        'times': 'x',
        'times-circle': 'x-circle',
        'plus-circle': 'plus-circle',
        'minus': 'minus',
        'minus-circle': 'minus-circle',
        'question': 'help-circle',
        'question-circle': 'help-circle',
        'envelope': 'mail',
        'envelope-open': 'mail-open',
        'phone': 'phone',
        'mobile': 'smartphone',
        'globe': 'globe',
        'location-arrow': 'navigation',
        'compass': 'compass',
        'history': 'history',
        'undo': 'undo',
        'forward': 'fast-forward',
        'backward': 'rewind',
        'step-forward': 'skip-forward',
        'step-backward': 'skip-back',
        'pause': 'pause',
        'stop': 'square',
        'volume-up': 'volume-2',
        'volume-down': 'volume-1',
        'volume-off': 'volume-x',
        'volume-mute': 'volume-x',
        // New mappings from your unmapped icons list
        'chevron-right': 'chevron-right',
        'coins': 'coins',
        'moon': 'moon',
        'ellipsis-v': 'more-vertical',
        'route': 'route',
        'arrow-left': 'arrow-left',
        'bell': 'bell',
        'scroll': 'scroll',
        'circle': 'circle',
        'medal': 'medal',
        'book': 'book',
        'circle-question': 'help-circle',
        'user-tie': 'user-check', // Closest equivalent
        'spinner': 'loader-2',
        'shapes': 'shapes',
        'balance-scale': 'scale',
        'eraser': 'eraser',
        'crosshairs': 'crosshair',
        'flag': 'flag',
        'lightbulb': 'lightbulb',
        'sliders-h': 'sliders-horizontal',
        'file-export': 'file-output',
        'magic': 'wand-2',
        'calculator': 'calculator',
        'puzzle-piece': 'puzzle',
        'hand-paper': 'hand',
        'copy': 'copy',
        'database': 'database',
        'arrow-down-a-z': 'arrow-down-a-z',
        'chalkboard-user': 'presentation',
        'expand': 'expand',
        'clipboard-check': 'clipboard-check',
        'hourglass-half': 'hourglass',
        'paper-plane': 'send',
        'graduation-cap': 'graduation-cap',
        'equals': 'equal',
        'circle-notch': 'loader',
        'sort-numeric-up': 'arrow-up-1-0',
        'arrow-down': 'arrow-down',
        'hashtag': 'hash',
        'skating': 'activity', // Close equivalent
        'pie-chart': 'pie-chart',
        'tasks': 'list-todo',
        'arrows-alt-h': 'move-horizontal',
        'th': 'grid-3x3',
        'power-off': 'power',
        'image': 'image',
        'cloud-upload-alt': 'cloud-upload',
        'heading': 'heading',
        'window-minimize': 'minimize-2',
        'paint-brush': 'paintbrush',
        'stamp': 'stamp',
        'briefcase': 'briefcase',
        'gem': 'gem',
        'shield-alt': 'shield',
        'angle-right': 'chevron-right',
        'user-plus': 'user-plus',
        'check-double': 'check-check',
        'building': 'building',
        'refresh': 'refresh-cw',
        'exchange-alt': 'repeat',
        'random': 'shuffle',
        'sort-alpha-down': 'arrow-down-a-z',
        'sort-numeric-down': 'arrow-down-0-1',
        'level-up-alt': 'corner-up-right',
        'hourglass': 'hourglass',
        'arrow-up': 'arrow-up',
        'stream': 'waves',
        'sort': 'arrow-up-down',
        'play-circle': 'play-circle',
        'bug': 'bug',
        'cloud-sun': 'cloud-sun',
        'tower-broadcast': 'radio',
        'broadcast-tower': 'radio',
        'flag-checkered': 'flag',
        'list-ol': 'list-ordered',
        'eye-slash': 'eye-off',
        'bell-slash': 'bell-off',
        'ban': 'ban',
        'chevron-up': 'chevron-up',
        'hand-rock': 'hand',
        'mountain': 'mountain',
        // Additional new mappings
        'skiing': 'mountain-snow',
        'snowboarding': 'mountain-snow',
        'columns': 'columns',
        'paste': 'clipboard-paste',
        'crown': 'crown',
        'calendar-check': 'calendar-check',
        'user-clock': 'user-clock',
        'users-cog': 'users-cog',
        'calendar-plus': 'calendar-plus',
        'th-large': 'grid-2x2',
        'share-alt': 'share',
        'list-alt': 'list',
        'tools': 'wrench',
        'tv': 'tv',
        'stopwatch': 'timer',
        'hourglass-start': 'hourglass',
        'user-circle': 'user-circle',
        'calendar-times': 'calendar-x'
    };

    /**
     * Main translation function
     * Finds all Font Awesome icons and converts them to Lucide
     * @param {Element} container - Optional container element to search within (defaults to document)
     */
    window.translateFAToLucide = function(container = document) {
        // Find all Font Awesome icons within the specified container
        const faIcons = container.querySelectorAll('i[class*="fas fa-"], i[class*="far fa-"], i[class*="fab fa-"], i[class*="fal fa-"], i[class*="fad fa-"]');
        
        let convertedCount = 0;
        let unmappedIcons = [];
        
        faIcons.forEach(icon => {
            // Extract the FA icon name
            const classList = Array.from(icon.classList);
            let faIconName = null;
            
            // Find the fa- class
            for (let className of classList) {
                if (className.startsWith('fa-') && 
                    className !== 'fa-2x' && 
                    className !== 'fa-3x' && 
                    className !== 'fa-lg' &&
                    className !== 'fa-sm' &&
                    className !== 'fa-xs') {
                    faIconName = className.substring(3); // Remove 'fa-' prefix
                    break;
                }
            }
            
            if (faIconName) {
                if (iconMap[faIconName]) {
                    // Create new Lucide icon element
                    const newIcon = document.createElement('i');
                    newIcon.setAttribute('data-lucide', iconMap[faIconName]);
                    
                    // Handle sizing classes
                    if (icon.classList.contains('fa-2x')) {
                        newIcon.style.width = '32px';
                        newIcon.style.height = '32px';
                    } else if (icon.classList.contains('fa-3x')) {
                        newIcon.style.width = '48px';
                        newIcon.style.height = '48px';
                    } else if (icon.classList.contains('fa-lg')) {
                        newIcon.style.width = '20px';
                        newIcon.style.height = '20px';
                    } else if (icon.classList.contains('fa-sm')) {
                        newIcon.style.width = '14px';
                        newIcon.style.height = '14px';
                    } else if (icon.classList.contains('fa-xs')) {
                        newIcon.style.width = '12px';
                        newIcon.style.height = '12px';
                    } else {
                        newIcon.style.width = '18px';
                        newIcon.style.height = '18px';
                    }
                    
                    // Preserve spacing, text color, and other utility classes
                    const preserveClasses = classList.filter(cls => 
                        cls.startsWith('me-') || 
                        cls.startsWith('ms-') || 
                        cls.startsWith('m-') ||
                        cls.startsWith('p-') ||
                        cls.startsWith('text-') ||
                        cls.includes('mb-') ||
                        cls.includes('mt-') ||
                        cls.includes('mx-') ||
                        cls.includes('my-') ||
                        cls === 'd-block' ||
                        cls === 'd-inline' ||
                        cls === 'd-inline-block' ||
                        cls.startsWith('bg-') ||
                        cls.startsWith('border-') ||
                        cls.startsWith('rounded') ||
                        cls.startsWith('shadow')
                    );
                    
                    if (preserveClasses.length > 0) {
                        newIcon.className = preserveClasses.join(' ');
                    }
                    
                    // Replace the old icon with the new one
                    icon.parentNode.replaceChild(newIcon, icon);
                    convertedCount++;
                } else {
                    // Collect unmapped icons for future reference
                    if (!unmappedIcons.includes(faIconName)) {
                        unmappedIcons.push(faIconName);
                    }
                    
                    // Add a data attribute to mark this as unmapped
                    icon.setAttribute('data-fa-unmapped', faIconName);
                    icon.title = `Font Awesome icon "${faIconName}" not mapped to Lucide`;
                    
                    // Optionally add a visual indicator (subtle border)
                    icon.style.border = '1px dashed #ffc107';
                    icon.style.borderRadius = '2px';
                }
            }
        });
        
        // Store unmapped icons in localStorage
        if (unmappedIcons.length > 0) {
            storeUnmappedIcons(unmappedIcons);
        }
        
        // Re-initialize Lucide icons
        if (window.lucide && typeof lucide.createIcons === 'function') {
            try {
                lucide.createIcons();
                if (convertedCount > 0 && window.console) {
                    console.log(`Converted ${convertedCount} Font Awesome icons to Lucide`);
                }
                if (unmappedIcons.length > 0 && window.console) {
                    console.warn(`Found ${unmappedIcons.length} unmapped Font Awesome icons:`, unmappedIcons);
                    console.log('Use window.getUnmappedIcons() to see all collected unmapped icons');
                }
            } catch (e) {
                if (window.console) {
                    console.warn('Error initializing Lucide icons:', e);
                }
            }
        }
        
        return {
            converted: convertedCount,
            unmapped: unmappedIcons.length,
            unmappedIcons: unmappedIcons
        };
    };

    /**
     * Store unmapped icons in localStorage
     */
    function storeUnmappedIcons(newUnmappedIcons) {
        try {
            const storageKey = 'fa-to-lucide-unmapped';
            const existingData = localStorage.getItem(storageKey);
            let unmappedData = {
                icons: [],
                lastUpdated: new Date().toISOString(),
                count: 0
            };
            
            if (existingData) {
                try {
                    unmappedData = JSON.parse(existingData);
                } catch (e) {
                    // Reset if corrupted
                    unmappedData = { icons: [], lastUpdated: new Date().toISOString(), count: 0 };
                }
            }
            
            // Add new unmapped icons (avoid duplicates)
            newUnmappedIcons.forEach(iconName => {
                const existingIcon = unmappedData.icons.find(item => item.name === iconName);
                if (existingIcon) {
                    existingIcon.count++;
                    existingIcon.lastSeen = new Date().toISOString();
                } else {
                    unmappedData.icons.push({
                        name: iconName,
                        count: 1,
                        firstSeen: new Date().toISOString(),
                        lastSeen: new Date().toISOString()
                    });
                }
            });
            
            unmappedData.lastUpdated = new Date().toISOString();
            unmappedData.count = unmappedData.icons.length;
            
            localStorage.setItem(storageKey, JSON.stringify(unmappedData));
        } catch (e) {
            if (window.console) {
                console.warn('Could not store unmapped icons in localStorage:', e);
            }
        }
    }

    /**
     * Initialize Lucide icons - call this after adding dynamic content
     */
    window.initializeLucideIcons = function() {
        if (window.lucide && typeof lucide.createIcons === 'function') {
            try {
                lucide.createIcons();
                return true;
            } catch (e) {
                if (window.console) {
                    console.warn('Error initializing Lucide icons:', e);
                }
                return false;
            }
        } else {
            if (window.console) {
                console.warn('Lucide library not available');
            }
            return false;
        }
    };

    /**
     * Utility function to handle dynamic content - translates FA icons and initializes Lucide
     */
    window.handleDynamicContent = function(container = document) {
        // First translate any FA icons in the new content
        const result = container === document ? 
            window.translateFAToLucide() : 
            window.translateFAToLucideInContainer(container);
        
        // Then initialize Lucide icons
        window.initializeLucideIcons();
        
        return result;
    };

    /**
     * Get all unmapped icons from localStorage
     */
    window.getUnmappedIcons = function() {
        try {
            const storageKey = 'fa-to-lucide-unmapped';
            const data = localStorage.getItem(storageKey);
            if (data) {
                const parsed = JSON.parse(data);
                console.table(parsed.icons.sort((a, b) => b.count - a.count));
                return parsed;
            } else {
                console.log('No unmapped icons found in localStorage');
                return null;
            }
        } catch (e) {
            console.error('Error reading unmapped icons from localStorage:', e);
            return null;
        }
    };

    /**
     * Clear unmapped icons from localStorage
     */
    window.clearUnmappedIcons = function() {
        try {
            localStorage.removeItem('fa-to-lucide-unmapped');
            console.log('Cleared unmapped icons from localStorage');
        } catch (e) {
            console.error('Error clearing unmapped icons:', e);
        }
    };

    /**
     * Export unmapped icons for developer use
     */
    window.exportUnmappedIcons = function() {
        const data = window.getUnmappedIcons();
        if (data && data.icons.length > 0) {
            const exportText = data.icons
                .sort((a, b) => b.count - a.count)
                .map(icon => `'${icon.name}': '', // Used ${icon.count} times`)
                .join('\n        ');
            
            const output = `// Add these to iconMap in fa-to-lucide.js:\n{\n        ${exportText}\n}`;
            console.log(output);
            
            // Copy to clipboard if available
            if (navigator.clipboard) {
                navigator.clipboard.writeText(output).then(() => {
                    console.log('Unmapped icons template copied to clipboard!');
                }).catch(err => {
                    console.warn('Could not copy to clipboard:', err);
                });
            }
            
            return output;
        } else {
            console.log('No unmapped icons to export');
            return null;
        }
    };

    /**
     * Auto-translate on DOM ready if enabled
     */
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            // Small delay to ensure Lucide is loaded
            setTimeout(function() {
                if (window.translateFAToLucide) {
                    window.translateFAToLucide();
                }
            }, 100);
        });
    } else {
        // DOM is already ready
        setTimeout(function() {
            if (window.translateFAToLucide) {
                window.translateFAToLucide();
            }
        }, 100);
    }

    /**
     * Utility function to translate FA icons in a specific container
     */
    window.translateFAToLucideInContainer = function(container) {
        if (!container) return 0;
        
        const faIcons = container.querySelectorAll('i[class*="fas fa-"], i[class*="far fa-"], i[class*="fab fa-"], i[class*="fal fa-"], i[class*="fad fa-"]');
        let convertedCount = 0;
        let unmappedIcons = [];
        
        faIcons.forEach(icon => {
            // Same logic as main function but scoped to container
            const classList = Array.from(icon.classList);
            let faIconName = null;
            
            for (let className of classList) {
                if (className.startsWith('fa-') && 
                    className !== 'fa-2x' && 
                    className !== 'fa-3x' && 
                    className !== 'fa-lg' &&
                    className !== 'fa-sm' &&
                    className !== 'fa-xs') {
                    faIconName = className.substring(3);
                    break;
                }
            }
            
            if (faIconName) {
                if (iconMap[faIconName]) {
                    const newIcon = document.createElement('i');
                    newIcon.setAttribute('data-lucide', iconMap[faIconName]);
                    
                    // Handle sizing and preserve classes (same as main function)
                    if (icon.classList.contains('fa-2x')) {
                        newIcon.style.width = '32px';
                        newIcon.style.height = '32px';
                    } else if (icon.classList.contains('fa-3x')) {
                        newIcon.style.width = '48px';
                        newIcon.style.height = '48px';
                    } else if (icon.classList.contains('fa-lg')) {
                        newIcon.style.width = '20px';
                        newIcon.style.height = '20px';
                    } else if (icon.classList.contains('fa-sm')) {
                        newIcon.style.width = '14px';
                        newIcon.style.height = '14px';
                    } else if (icon.classList.contains('fa-xs')) {
                        newIcon.style.width = '12px';
                        newIcon.style.height = '12px';
                    } else {
                        newIcon.style.width = '18px';
                        newIcon.style.height = '18px';
                    }
                    
                    const preserveClasses = classList.filter(cls => 
                        cls.startsWith('me-') || 
                        cls.startsWith('ms-') || 
                        cls.startsWith('m-') ||
                        cls.startsWith('p-') ||
                        cls.startsWith('text-') ||
                        cls.includes('mb-') ||
                        cls.includes('mt-') ||
                        cls.includes('mx-') ||
                        cls.includes('my-') ||
                        cls === 'd-block' ||
                        cls === 'd-inline' ||
                        cls === 'd-inline-block' ||
                        cls.startsWith('bg-') ||
                        cls.startsWith('border-') ||
                        cls.startsWith('rounded') ||
                        cls.startsWith('shadow')
                    );
                    
                    if (preserveClasses.length > 0) {
                        newIcon.className = preserveClasses.join(' ');
                    }
                    
                    icon.parentNode.replaceChild(newIcon, icon);
                    convertedCount++;
                } else {
                    // Collect unmapped icons
                    if (!unmappedIcons.includes(faIconName)) {
                        unmappedIcons.push(faIconName);
                    }
                    
                    // Mark as unmapped
                    icon.setAttribute('data-fa-unmapped', faIconName);
                    icon.title = `Font Awesome icon "${faIconName}" not mapped to Lucide`;
                    icon.style.border = '1px dashed #ffc107';
                    icon.style.borderRadius = '2px';
                }
            }
        });
        
        // Store unmapped icons
        if (unmappedIcons.length > 0) {
            storeUnmappedIcons(unmappedIcons);
        }
        
        // Re-initialize Lucide icons in the container
        if (window.lucide && typeof lucide.createIcons === 'function') {
            try {
                lucide.createIcons();
            } catch (e) {
                if (window.console) {
                    console.warn('Error initializing Lucide icons:', e);
                }
            }
        }
        
        return {
            converted: convertedCount,
            unmapped: unmappedIcons.length,
            unmappedIcons: unmappedIcons
        };
    };

    // Utility function for dynamic content - safe Lucide initialization
    window.initializeLucideIcons = function(container) {
        if (window.lucide && typeof lucide.createIcons === 'function') {
            try {
                // Convert any new Font Awesome icons to Lucide first
                if (typeof window.convertFontAwesomeToLucide === 'function') {
                    window.convertFontAwesomeToLucide(container);
                }
                
                // Then initialize Lucide icons
                lucide.createIcons();
            } catch (e) {
                if (window.console) {
                    console.warn('Error initializing Lucide icons:', e);
                }
            }
        }
    };

    // Alias for backward compatibility and clearer naming
    window.convertFontAwesomeToLucide = function(container) {
        if (container && container !== document) {
            return window.translateFAToLucideInContainer(container);
        } else {
            return window.translateFAToLucide(container);
        }
    };

    // Helper for handling dynamic content updates
    window.handleDynamicContent = function(element) {
        if (element && window.initializeLucideIcons) {
            window.initializeLucideIcons();
        }
    };

})();
