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

async function debugNavigation() {
  console.log('🔍 Debugging navigation admin detection...');
  
  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()}`));
  
  try {
    // Login first
    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"]');
    await page.waitForTimeout(5000);
    
    // Go to dashboard
    await page.goto('http://localhost:3000/dashboard', { waitUntil: 'networkidle' });
    await page.waitForTimeout(3000);
    
    // Run detailed debug of the admin detection
    const debugResult = await page.evaluate(async () => {
      try {
        console.log('[DEBUG] Starting detailed admin detection...');
        
        const response = await fetch('/api/auth/user');
        console.log('[DEBUG] Response status:', response.status);
        
        if (!response.ok) {
          return { error: 'API call failed', status: response.status };
        }
        
        const userData = await response.json();
        console.log('[DEBUG] Raw userData:', userData);
        console.log('[DEBUG] userData.profile:', userData.profile);
        console.log('[DEBUG] userData.profile?.role:', userData.profile?.role);
        console.log('[DEBUG] typeof userData.profile?.role:', typeof userData.profile?.role);
        console.log('[DEBUG] userData.profile?.role === "admin":', userData.profile?.role === 'admin');
        
        // Test different ways to check admin
        const checks = {
          profileExists: !!userData.profile,
          roleExists: !!userData.profile?.role,
          roleValue: userData.profile?.role,
          roleTypeOf: typeof userData.profile?.role,
          strictEqual: userData.profile?.role === 'admin',
          looseEqual: userData.profile?.role == 'admin',
          toLowerCase: userData.profile?.role?.toLowerCase() === 'admin',
          includes: userData.profile?.role?.includes('admin')
        };
        
        console.log('[DEBUG] All checks:', checks);
        
        return { 
          success: true, 
          userData, 
          checks,
          isAdmin: userData.profile?.role === 'admin'
        };
        
      } catch (error) {
        console.error('[DEBUG] Error:', error);
        return { error: error.message };
      }
    });
    
    console.log('\n=== DEBUG RESULTS ===');
    console.log(JSON.stringify(debugResult, null, 2));
    
  } catch (error) {
    console.error('❌ Debug failed:', error);
  } finally {
    await browser.close();
  }
}

debugNavigation().catch(console.error);