const fs = require('fs');
const https = require('https');
const http = require('http');

// Test the calendar page for common issues
async function diagnoseCalendarIssues() {
    console.log('🔍 Diagnosing Black Canyon Tickets Calendar Issues...\n');
    
    const testUrl = 'http://localhost:4321/calendar';
    
    try {
        // Fetch the HTML
        const html = await fetchPage(testUrl);
        
        console.log('📄 HTML Analysis:');
        console.log('- HTML Length:', html.length, 'bytes');
        
        // Check for theme initialization
        const hasThemeScript = html.includes('data-theme');
        console.log('- Theme Initialization:', hasThemeScript ? '✅' : '❌');
        
        // Check for CSS variables usage
        const hasCSSVariables = html.includes('var(--bg-gradient)');
        console.log('- CSS Variables Found:', hasCSSVariables ? '✅' : '❌');
        
        // Check for hero section
        const hasHeroSection = html.includes('id="hero-section"');
        console.log('- Hero Section:', hasHeroSection ? '✅' : '❌');
        
        // Check for theme toggle
        const hasThemeToggle = html.includes('id="theme-toggle"');
        console.log('- Theme Toggle:', hasThemeToggle ? '✅' : '❌');
        
        // Check for calendar-specific elements
        const hasCalendarGrid = html.includes('id="calendar-grid"');
        console.log('- Calendar Grid:', hasCalendarGrid ? '✅' : '❌');
        
        // Check for loading state
        const hasLoadingState = html.includes('id="loading-state"');
        console.log('- Loading State:', hasLoadingState ? '✅' : '❌');
        
        // Check for JavaScript errors (look for script tags)
        const scriptCount = (html.match(/<script/g) || []).length;
        console.log('- Script Tags Count:', scriptCount);
        
        console.log('\n🎨 Theme System Analysis:');
        
        // Extract and analyze the theme initialization script
        const themeScriptMatch = html.match(/\(function\(\)\s*{[\s\S]*?data-theme[\s\S]*?}\)\(\);/);
        if (themeScriptMatch) {
            console.log('- Theme Script Found: ✅');
            console.log('- Contains localStorage check:', themeScriptMatch[0].includes('localStorage') ? '✅' : '❌');
            console.log('- Sets data-theme attribute:', themeScriptMatch[0].includes('setAttribute') ? '✅' : '❌');
        } else {
            console.log('- Theme Script: ❌ NOT FOUND');
        }
        
        // Check for CSS imports
        const cssImports = html.match(/import.*\.css/g) || [];
        console.log('- CSS Imports:', cssImports.length);
        cssImports.forEach(imp => console.log('  -', imp));
        
        console.log('\n🚨 Potential Issues:');
        
        const issues = [];
        
        // Check for theme system issues
        if (!hasThemeScript) {
            issues.push('❌ Theme initialization script missing');
        }
        
        if (!hasThemeToggle) {
            issues.push('❌ Theme toggle button missing');
        }
        
        // Check for CSS variable issues in light mode
        if (html.includes('[data-theme="light"] [style*="background: var(--bg-gradient)"]')) {
            console.log('✅ Light mode CSS override found');
        } else {
            issues.push('❌ Light mode background override missing');
        }
        
        // Check for FOUC prevention
        if (!html.includes('prevents FOUC')) {
            issues.push('⚠️ FOUC prevention comment missing');
        }
        
        // Check for accessibility imports
        if (html.includes('accessibility')) {
            console.log('✅ Accessibility imports found');
        } else {
            issues.push('⚠️ Accessibility imports missing');
        }
        
        if (issues.length === 0) {
            console.log('✅ No obvious issues detected');
        } else {
            issues.forEach(issue => console.log(issue));
        }
        
        console.log('\n🔧 Recommendations:');
        
        // Fresh browser simulation
        console.log('1. Test with fresh browser state:');
        console.log('   - Clear localStorage');
        console.log('   - Disable cache');
        console.log('   - Test in incognito mode');
        
        console.log('2. Verify theme initialization:');
        console.log('   - Check browser console for errors');
        console.log('   - Verify data-theme attribute is set');
        console.log('   - Test with both light and dark preferences');
        
        console.log('3. Check CSS loading order:');
        console.log('   - Ensure glassmorphism.css loads after global.css');
        console.log('   - Verify CSS variables are defined');
        console.log('   - Test on slow network connections');
        
        console.log('4. Test JavaScript execution:');
        console.log('   - Check for script errors in console');
        console.log('   - Verify event listeners are attached');
        console.log('   - Test theme toggle functionality');
        
        console.log('\n🌐 Network Test:');
        await testNetworkConditions(testUrl);
        
    } catch (error) {
        console.error('❌ Error:', error.message);
    }
}

function fetchPage(url) {
    return new Promise((resolve, reject) => {
        const client = url.startsWith('https:') ? https : http;
        
        client.get(url, (res) => {
            let data = '';
            res.on('data', chunk => data += chunk);
            res.on('end', () => resolve(data));
        }).on('error', reject);
    });
}

async function testNetworkConditions(baseUrl) {
    const endpoints = [
        '/calendar',
        '/src/styles/glassmorphism.css',
        '/src/styles/global.css',
        '/api/public/events'
    ];
    
    for (const endpoint of endpoints) {
        try {
            const url = baseUrl.replace('/calendar', '') + endpoint;
            const start = Date.now();
            
            await new Promise((resolve, reject) => {
                const client = url.startsWith('https:') ? https : http;
                client.get(url, (res) => {
                    const duration = Date.now() - start;
                    console.log(`- ${endpoint}: ${res.statusCode} (${duration}ms)`);
                    res.on('data', () => {}); // Consume response
                    res.on('end', resolve);
                }).on('error', () => {
                    console.log(`- ${endpoint}: ❌ Failed to load`);
                    resolve();
                });
            });
        } catch (e) {
            console.log(`- ${endpoint}: ❌ Error`);
        }
    }
}

// Run the diagnosis
if (require.main === module) {
    diagnoseCalendarIssues().catch(console.error);
}

module.exports = { diagnoseCalendarIssues };