const puppeteer = require('puppeteer');

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

        const page = await browser.newPage();
        
        const consoleErrors = [];
        page.on('console', msg => {
            const type = msg.type();
            if (type === 'error') {
                consoleErrors.push(msg.text());
                console.log(`🚨 Console Error: ${msg.text()}`);
            }
        });

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

        // Test 1: Login
        console.log('1️⃣ Testing Login Flow...');
        await page.goto('http://localhost:3000/login', { waitUntil: 'networkidle2' });
        await page.screenshot({ path: 'verification-login-page.png' });
        
        await page.waitForSelector('input[type="email"]', { timeout: 5000 });
        await page.type('input[type="email"]', 'tmartinez@gmail.com');
        await page.type('input[type="password"]', 'Skittles@420');
        
        await page.screenshot({ path: 'verification-login-filled.png' });
        
        await page.click('button[type="submit"]');
        await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 10000 });
        
        const dashboardUrl = page.url();
        console.log(`   Current URL after login: ${dashboardUrl}`);
        
        if (dashboardUrl.includes('/dashboard')) {
            console.log('   ✅ Login successful - redirected to dashboard');
            await page.screenshot({ path: 'verification-dashboard-success.png' });
        } else {
            console.log('   ❌ Login failed or incorrect redirect');
            await page.screenshot({ path: 'verification-login-failed.png' });
            return;
        }

        // Test 2: QR Scanner
        console.log('\n2️⃣ Testing QR Scanner (/scan)...');
        await page.goto('http://localhost:3000/scan', { waitUntil: 'networkidle2' });
        await page.screenshot({ path: 'verification-scanner.png' });
        
        const scannerUrl = page.url();
        const scannerTitle = await page.title();
        const scannerContent = await page.$eval('body', el => el.textContent.toLowerCase());
        
        console.log(`   Scanner URL: ${scannerUrl}`);
        console.log(`   Scanner Title: ${scannerTitle}`);
        
        if (scannerUrl.includes('/scan') && !scannerUrl.includes('/login')) {
            if (scannerContent.includes('scan') || scannerContent.includes('qr') || scannerContent.includes('camera')) {
                console.log('   ✅ Scanner loads properly with scan interface');
            } else {
                console.log('   ⚠️ Scanner loads but may not show camera interface');
            }
        } else {
            console.log('   ❌ Scanner redirects away from /scan');
        }

        // Test 3: Templates
        console.log('\n3️⃣ Testing Templates (/templates)...');
        await page.goto('http://localhost:3000/templates', { waitUntil: 'networkidle2' });
        await page.screenshot({ path: 'verification-templates.png' });
        
        const templatesUrl = page.url();
        const templatesTitle = await page.title();
        
        console.log(`   Templates URL: ${templatesUrl}`);
        console.log(`   Templates Title: ${templatesTitle}`);
        
        if (templatesUrl.includes('/templates') && !templatesUrl.includes('/login')) {
            console.log('   ✅ Templates loads without redirecting to login');
        } else {
            console.log('   ❌ Templates redirects to login');
        }

        // Test 4: Calendar
        console.log('\n4️⃣ Testing Calendar (/calendar)...');
        await page.goto('http://localhost:3000/calendar', { waitUntil: 'networkidle2' });
        await page.screenshot({ path: 'verification-calendar.png' });
        
        const calendarUrl = page.url();
        const calendarTitle = await page.title();
        const calendarContent = await page.$eval('body', el => el.textContent.toLowerCase());
        
        console.log(`   Calendar URL: ${calendarUrl}`);
        console.log(`   Calendar Title: ${calendarTitle}`);
        
        if (calendarUrl.includes('/calendar')) {
            if (calendarContent.includes('calendar') || calendarContent.includes('event')) {
                console.log('   ✅ Calendar loads with calendar content');
            } else {
                console.log('   ⚠️ Calendar loads but may be blank');
            }
        } else {
            console.log('   ❌ Calendar redirects away');
        }

        // Test 5: Check for events and test management
        console.log('\n5️⃣ Testing Event Management...');
        await page.goto('http://localhost:3000/dashboard', { waitUntil: 'networkidle2' });
        
        const eventLinks = await page.$$('a[href*="/events/"][href*="/manage"]');
        
        if (eventLinks.length > 0) {
            const firstEventHref = await page.evaluate(el => el.href, eventLinks[0]);
            console.log(`   Found event to test: ${firstEventHref}`);
            
            await page.goto(firstEventHref, { waitUntil: 'networkidle2' });
            await page.screenshot({ path: 'verification-event-manage.png' });
            
            const manageContent = await page.$eval('body', el => el.textContent.toLowerCase());
            
            if (manageContent.includes('revenue') || manageContent.includes('tickets sold') || manageContent.includes('stats')) {
                console.log('   ✅ Event management loads with stats');
            } else {
                console.log('   ⚠️ Event management loads but stats may be missing');
            }
        } else {
            console.log('   ⚠️ No events found to test management');
            await page.screenshot({ path: 'verification-no-events.png' });
        }

        // Summary
        console.log('\n📊 VERIFICATION SUMMARY:');
        console.log('========================');
        if (consoleErrors.length > 0) {
            console.log(`🚨 Console Errors Found: ${consoleErrors.length}`);
            consoleErrors.forEach((error, i) => console.log(`   ${i+1}. ${error}`));
        } else {
            console.log('✅ No critical console errors detected');
        }

        console.log('\n🎯 All screenshots saved as verification-*.png');
        console.log('📝 Manual review recommended for final assessment');

    } catch (error) {
        console.error('❌ Test failed:', error.message);
        if (browser) {
            await browser.close();
        }
    } finally {
        if (browser) {
            setTimeout(() => {
                browser.close();
                console.log('\n🔧 Browser closed - test complete');
            }, 2000);
        }
    }
}

runSimpleVerification();