const { TradingViewAutomation } = require('./lib/tradingview-automation.ts');

async function testUpdatedLogin() {
  console.log('🚀 Testing updated login logic...');
  
  const automation = new TradingViewAutomation();
  
  try {
    console.log('⏳ Initializing automation...');
    await automation.initialize();
    
    console.log('🔐 Testing login...');
    const loginResult = await automation.login();
    
    if (loginResult) {
      console.log('✅ Login successful!');
      
      // Test if we can get user-specific content
      console.log('🔍 Checking authentication status...');
      const isAuthenticated = await automation.checkLoginStatus();
      console.log('🔐 Authentication status:', isAuthenticated);
      
      // Take a screenshot to see what page we're on
      await automation.takeDebugScreenshot('after_login_test');
      
      // Check current URL
      const currentUrl = await automation.page.url();
      console.log('📍 Current URL:', currentUrl);
      
      // Try to navigate to a page that requires authentication
      console.log('📊 Testing navigation to TradingView chart...');
      await automation.page.goto('https://www.tradingview.com/chart/', { waitUntil: 'domcontentloaded' });
      await automation.page.waitForTimeout(5000);
      
      // Take another screenshot
      await automation.takeDebugScreenshot('chart_page_after_login');
      
      // Check if we see user-specific elements
      const userElements = await automation.page.evaluate(() => {
        const userMenu = document.querySelector('.tv-header__user-menu-button, [data-name="header-user-menu"]');
        const guestIndicators = document.querySelectorAll('[class*="anonymous"], [class*="guest"]');
        
        return {
          hasUserMenu: !!userMenu,
          userMenuText: userMenu?.textContent || '',
          guestCount: guestIndicators.length,
          pageTitle: document.title,
          bodyText: document.body.textContent?.slice(0, 500) || ''
        };
      });
      
      console.log('👤 User elements check:', userElements);
      
    } else {
      console.log('❌ Login failed');
    }
    
  } catch (error) {
    console.error('💥 Error during login test:', error);
  } finally {
    console.log('🧹 Cleaning up...');
    await automation.cleanup();
  }
}

testUpdatedLogin().catch(console.error);
