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

async function runFinalVerification() {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: { width: 1200, height: 800 },
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });

    const page = await browser.newPage();
    
    // Enable console logging
    page.on('console', msg => {
        const type = msg.type();
        if (['error', 'warn'].includes(type)) {
            console.log(`[${type.toUpperCase()}] ${msg.text()}`);
        }
    });

    const results = {
        login: { status: '❌', errors: [] },
        scanner: { status: '❌', errors: [] },
        templates: { status: '❌', errors: [] },
        calendar: { status: '❌', errors: [] },
        eventManagement: { status: '❌', errors: [] }
    };

    try {
        console.log('🚀 Starting Final Verification Test...\n');

        // Test 1: Login
        console.log('1️⃣ Testing Login...');
        await page.goto('http://localhost:3000/login');
        await page.waitForSelector('form');
        
        await page.type('input[type="email"]', 'tmartinez@gmail.com');
        await page.type('input[type="password"]', 'Skittles@420');
        
        await page.screenshot({ path: 'verification-login-form.png' });
        
        await page.click('button[type="submit"]');
        await page.waitForNavigation({ waitUntil: 'networkidle0' });
        
        const currentUrl = page.url();
        if (currentUrl.includes('/dashboard')) {
            results.login.status = '✅';
            console.log('   ✅ Login successful - redirected to dashboard');
        } else {
            results.login.status = '❌';
            console.log(`   ❌ Login failed - ended up at: ${currentUrl}`);
        }
        
        await page.screenshot({ path: 'verification-dashboard.png' });

        // Test 2: QR Scanner
        console.log('\n2️⃣ Testing QR Scanner...');
        await page.goto('http://localhost:3000/scan');
        await page.waitForSelector('body', { timeout: 5000 });
        
        const scannerContent = await page.content();
        if (scannerContent.includes('scanner') || scannerContent.includes('QR') || scannerContent.includes('camera')) {
            results.scanner.status = '✅';
            console.log('   ✅ Scanner page loads scanner interface');
        } else if (scannerContent.includes('Welcome to Black Canyon Tickets')) {
            results.scanner.status = '❌';
            console.log('   ❌ Scanner redirects to homepage');
        } else {
            results.scanner.status = '⚠️';
            console.log('   ⚠️ Scanner page unclear content');
        }
        
        await page.screenshot({ path: 'verification-scanner.png' });

        // Test 3: Templates
        console.log('\n3️⃣ Testing Templates...');
        await page.goto('http://localhost:3000/templates');
        await page.waitForSelector('body', { timeout: 5000 });
        
        const templatesUrl = page.url();
        const templatesContent = await page.content();
        
        if (templatesUrl.includes('/login')) {
            results.templates.status = '❌';
            console.log('   ❌ Templates redirects to login');
        } else if (templatesContent.includes('template') || templatesContent.includes('Templates')) {
            results.templates.status = '✅';
            console.log('   ✅ Templates page loads properly');
        } else {
            results.templates.status = '⚠️';
            console.log('   ⚠️ Templates page unclear content');
        }
        
        await page.screenshot({ path: 'verification-templates.png' });

        // Test 4: Calendar
        console.log('\n4️⃣ Testing Calendar...');
        await page.goto('http://localhost:3000/calendar');
        await page.waitForSelector('body', { timeout: 5000 });
        
        const calendarContent = await page.content();
        const hasCalendarGrid = await page.$('.calendar-grid, .calendar, [class*="calendar"]');
        
        if (hasCalendarGrid || calendarContent.includes('calendar') || calendarContent.includes('Calendar')) {
            results.calendar.status = '✅';
            console.log('   ✅ Calendar page shows calendar interface');
        } else {
            results.calendar.status = '❌';
            console.log('   ❌ Calendar page shows blank or incorrect content');
        }
        
        await page.screenshot({ path: 'verification-calendar.png' });

        // Test 5: Event Management
        console.log('\n5️⃣ Testing Event Management...');
        
        // First, get an event ID from dashboard
        await page.goto('http://localhost:3000/dashboard');
        await page.waitForSelector('body', { timeout: 5000 });
        
        const eventLink = await page.$('a[href*="/events/"][href*="/manage"]');
        if (eventLink) {
            const href = await page.evaluate(el => el.href, eventLink);
            console.log(`   Found event link: ${href}`);
            
            await page.goto(href);
            await page.waitForSelector('body', { timeout: 5000 });
            
            const manageContent = await page.content();
            const hasStats = manageContent.includes('stats') || manageContent.includes('Revenue') || manageContent.includes('Tickets Sold');
            
            if (hasStats) {
                results.eventManagement.status = '✅';
                console.log('   ✅ Event management page loads with stats');
            } else {
                results.eventManagement.status = '❌';
                console.log('   ❌ Event management page missing stats');
            }
            
            await page.screenshot({ path: 'verification-event-management.png' });
        } else {
            results.eventManagement.status = '⚠️';
            console.log('   ⚠️ No events found to test management page');
            await page.screenshot({ path: 'verification-no-events.png' });
        }

        // Collect console errors
        const errors = [];
        page.on('pageerror', error => {
            errors.push(error.message);
        });

        console.log('\n📊 FINAL VERIFICATION RESULTS:');
        console.log('================================');
        console.log(`Login:            ${results.login.status}`);
        console.log(`QR Scanner:       ${results.scanner.status}`);
        console.log(`Templates:        ${results.templates.status}`);
        console.log(`Calendar:         ${results.calendar.status}`);
        console.log(`Event Management: ${results.eventManagement.status}`);
        
        const successCount = Object.values(results).filter(r => r.status === '✅').length;
        const totalTests = Object.keys(results).length;
        
        console.log(`\n🎯 Overall Success Rate: ${successCount}/${totalTests} (${Math.round(successCount/totalTests*100)}%)`);
        
        if (errors.length > 0) {
            console.log('\n🚨 Console Errors Found:');
            errors.forEach(error => console.log(`   - ${error}`));
        } else {
            console.log('\n✅ No critical console errors detected');
        }

    } catch (error) {
        console.error('❌ Test failed:', error.message);
    } finally {
        await browser.close();
    }
}

runFinalVerification();