const fs = require('fs');
const path = require('path');

class CSSFallbackFixer {
    constructor() {
        this.variableMap = {
            // Primary colors
            '--hvac-primary': '#0274be',
            '--hvac-primary-dark': '#005fa3',
            '--hvac-primary-light': '#e6f3fb',
            
            // Secondary colors
            '--hvac-secondary': '#54595f',
            '--hvac-secondary-dark': '#3a3f44',
            '--hvac-secondary-light': '#f0f0f1',
            
            // Success/Error colors
            '--hvac-success': '#4caf50',
            '--hvac-success-light': '#e8f5e9',
            '--hvac-error': '#d63638',
            '--hvac-error-light': '#ffebe9',
            
            // Neutral colors
            '--hvac-border': '#e0e0e0',
            '--hvac-border-light': '#f0f0f0',
            '--hvac-text': '#333333',
            '--hvac-text-light': '#757575',
            
            // Spacing
            '--hvac-spacing-xs': '0.25rem',
            '--hvac-spacing-sm': '0.5rem',
            '--hvac-spacing-md': '1rem',
            '--hvac-spacing-lg': '1.5rem',
            '--hvac-spacing-xl': '2rem',
            
            // Border radius
            '--hvac-border-radius': '4px',
            '--hvac-border-radius-lg': '8px',
            '--hvac-radius-sm': '4px',
            '--hvac-radius-md': '8px',
            '--hvac-radius-lg': '12px',
            
            // Box shadow
            '--hvac-shadow': '0 2px 4px rgba(0, 0, 0, 0.1)',
            '--hvac-shadow-lg': '0 4px 8px rgba(0, 0, 0, 0.1)',
            
            // Focus styles
            '--hvac-focus-color': '#2271b1',
            '--hvac-focus-width': '2px',
            '--hvac-focus-offset': '2px',
            
            // Dashboard specific variables
            '--hvac-spacing-1': '0.25rem',
            '--hvac-spacing-2': '0.5rem',
            '--hvac-spacing-3': '0.75rem',
            '--hvac-spacing-4': '1rem',
            '--hvac-spacing-5': '1.5rem',
            '--hvac-spacing-6': '2rem',
            '--hvac-spacing-8': '3rem',
            '--hvac-theme-primary': '#0073aa',
            '--hvac-theme-primary-dark': '#005a87',
            '--hvac-theme-text': '#333333'
        };
        
        this.processedFiles = [];
        this.totalReplacements = 0;
    }

    fixFile(filePath) {
        if (!fs.existsSync(filePath)) {
            console.log(`⚠️  File not found: ${filePath}`);
            return;
        }

        console.log(`\n🔧 Processing: ${path.basename(filePath)}`);
        
        let content = fs.readFileSync(filePath, 'utf8');
        let replacements = 0;
        
        // Find all var() usages and add fallbacks
        const varPattern = /([\w-]+)\s*:\s*(var\(--[\w-]+)\)/g;
        
        content = content.replace(varPattern, (match, property, varUsage) => {
            // Extract the CSS variable name
            const varName = varUsage.match(/var\((--[\w-]+)/);
            if (!varName || !varName[1]) return match;
            
            const cssVar = varName[1];
            const fallbackValue = this.variableMap[cssVar];
            
            if (fallbackValue) {
                replacements++;
                // Add fallback before the var() usage
                return `${property}: ${fallbackValue}; /* IE fallback */\n    ${property}: ${varUsage})`;
            }
            
            return match;
        });
        
        // Also handle cases where var() is used in composite values
        const compositeVarPattern = /([\w-]+)\s*:\s*([^;]*var\(--[\w-]+[^;]*);/g;
        
        content = content.replace(compositeVarPattern, (match, property, value) => {
            const varMatches = value.match(/var\((--[\w-]+)\)/g);
            if (!varMatches) return match;
            
            let fallbackValue = value;
            let hasFallback = false;
            
            varMatches.forEach(varMatch => {
                const varName = varMatch.match(/var\((--[\w-]+)/);
                if (varName && varName[1] && this.variableMap[varName[1]]) {
                    fallbackValue = fallbackValue.replace(varMatch, this.variableMap[varName[1]]);
                    hasFallback = true;
                }
            });
            
            if (hasFallback) {
                replacements++;
                return `${property}: ${fallbackValue}; /* IE fallback */\n    ${property}: ${value};`;
            }
            
            return match;
        });
        
        // Write the updated content back to the file
        fs.writeFileSync(filePath, content, 'utf8');
        
        console.log(`  ✅ Added ${replacements} fallbacks`);
        this.totalReplacements += replacements;
        this.processedFiles.push({
            file: path.basename(filePath),
            replacements: replacements
        });
    }

    generateReport() {
        console.log('\n' + '='.repeat(60));
        console.log('📋 CSS FALLBACK FIXES APPLIED');
        console.log('='.repeat(60));
        
        this.processedFiles.forEach(file => {
            console.log(`  ${file.file}: ${file.replacements} fallbacks added`);
        });
        
        console.log(`\n✅ Total fallbacks added: ${this.totalReplacements}`);
        console.log(`📁 Files processed: ${this.processedFiles.length}`);
        
        console.log('\n💡 What was fixed:');
        console.log('  • Added IE fallback values before all CSS custom property usages');
        console.log('  • Maintained existing var() declarations for modern browsers');
        console.log('  • Added comments to identify fallback values');
        console.log('  • Preserved all original functionality');
    }
}

// Execute the fixes
const fixer = new CSSFallbackFixer();
const cssFiles = [
    './assets/css/hvac-common.css',
    './assets/css/hvac-dashboard.css',
    './assets/css/hvac-registration.css',
    './assets/css/hvac-certificates.css',
    './assets/css/hvac-email-attendees.css',
    './assets/css/hvac-event-summary.css',
    './assets/css/hvac-attendee-profile.css',
    './assets/css/hvac-mobile-nav.css',
    './assets/css/hvac-animations.css',
    './assets/css/hvac-print.css'
];

console.log('🚀 Starting CSS Custom Properties Fallback Fixes...\n');

cssFiles.forEach(file => {
    fixer.fixFile(file);
});

fixer.generateReport();