const { chromium } = require('playwright');

async function testDashboardNavigation() {
  console.log('🧪 Testing dashboard navigation...');
  
  const browser = await chromium.launch({ 
    headless: false,
    slowMo: 1000
  });
  
  const context = await browser.newContext({
    viewport: { width: 1280, height: 720 }
  });
  
  const page = await context.newPage();
  
  // Enable console logging
  page.on('console', msg => console.log(`[PAGE] ${msg.text()}`));
  page.on('pageerror', err => console.error(`[PAGE ERROR] ${err}`));
  page.on('response', response => {
    console.log(`[RESPONSE] ${response.status()} ${response.url()}`);
  });
  
  try {
    // First login
    console.log('\n🔑 Step 1: Logging in...');
    await page.goto('http://localhost:3000/login-new', { waitUntil: 'networkidle' });
    
    await page.fill('#email', 'tmartinez@gmail.com');
    await page.fill('#password', 'Skittles@420');
    await page.click('button[type="submit"]');
    
    // Wait for login to complete
    await page.waitForTimeout(3000);
    console.log(`After login: ${page.url()}`);
    
    // Test admin dashboard
    console.log('\n👑 Step 2: Testing admin dashboard...');
    await page.goto('http://localhost:3000/admin/dashboard', { waitUntil: 'networkidle' });
    await page.waitForTimeout(2000);
    
    console.log(`Admin dashboard URL: ${page.url()}`);
    if (page.url().includes('/admin/dashboard')) {
      console.log('✅ Admin dashboard accessible');
      await page.screenshot({ path: 'admin-dashboard.png' });
    } else if (page.url().includes('/login')) {
      console.log('❌ Admin dashboard redirected to login');
      await page.screenshot({ path: 'admin-redirect-to-login.png' });
    }
    
    // Test regular dashboard
    console.log('\n📊 Step 3: Testing regular dashboard...');
    await page.goto('http://localhost:3000/dashboard', { waitUntil: 'networkidle' });
    await page.waitForTimeout(2000);
    
    console.log(`Regular dashboard URL: ${page.url()}`);
    if (page.url().includes('/dashboard') && !page.url().includes('/admin')) {
      console.log('✅ Regular dashboard accessible');
      await page.screenshot({ path: 'regular-dashboard.png' });
    } else if (page.url().includes('/login')) {
      console.log('❌ Regular dashboard redirected to login');
      await page.screenshot({ path: 'regular-redirect-to-login.png' });
    }
    
    // Check auth status
    console.log('\n🔍 Step 4: Checking auth status...');
    const authResponse = await page.goto('http://localhost:3000/api/auth/session', { waitUntil: 'networkidle' });
    const authData = await authResponse.json();
    console.log('Auth status:', authData);
    
  } catch (error) {
    console.error('❌ Test failed:', error);
    await page.screenshot({ path: 'navigation-error.png' });
  } finally {
    await browser.close();
  }
}

testDashboardNavigation().catch(console.error);