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

async function debugTradingViewLoginV2() {
  console.log('🚀 Starting TradingView login debug v2...');
  
  const browser = await chromium.launch({ 
    headless: false,  // Show the browser
    slowMo: 500,      // Slow down by 500ms
    devtools: true    // Open devtools
  });
  
  const context = await browser.newContext({
    viewport: { width: 1280, height: 720 },
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
  });
  
  const page = await context.newPage();
  
  try {
    console.log('📍 Navigating to TradingView login page...');
    await page.goto('https://www.tradingview.com/accounts/signin/', { 
      waitUntil: 'networkidle',
      timeout: 30000 
    });
    
    console.log('📄 Current URL:', page.url());
    console.log('📋 Page title:', await page.title());
    
    // Wait for dynamic content to load - try different strategies
    console.log('⏳ Waiting for dynamic content to load...');
    
    // Strategy 1: Wait for common login form selectors to appear
    const possibleSelectors = [
      'input[type="email"]',
      'input[name="email"]',
      'input[placeholder*="email" i]',
      '[data-name="email"]',
      'form input',
      '.login-form input',
      '#email',
      '[name="username"]'
    ];
    
    console.log('🔍 Waiting for login form to appear...');
    let loginFormFound = false;
    let foundSelector = null;
    
    // Try waiting for each selector with a reasonable timeout
    for (const selector of possibleSelectors) {
      try {
        console.log(`  Checking selector: ${selector}`);
        await page.waitForSelector(selector, { timeout: 3000, state: 'visible' });
        console.log(`✅ Found login form with selector: ${selector}`);
        foundSelector = selector;
        loginFormFound = true;
        break;
      } catch (e) {
        console.log(`  ❌ Selector ${selector} not found or not visible`);
      }
    }
    
    if (!loginFormFound) {
      console.log('⏰ No standard selectors found, waiting longer for page to fully load...');
      await page.waitForTimeout(10000); // Wait 10 seconds
    }
    
    // Take another screenshot after waiting
    await page.screenshot({ path: './debug-tradingview-after-wait.png', fullPage: true });
    console.log('📸 Screenshot saved as debug-tradingview-after-wait.png');
    
    // Check again for inputs after waiting
    console.log('🔍 Checking for input elements again...');
    const allInputs = await page.locator('input').all();
    console.log(`📝 Found ${allInputs.length} total input elements after waiting`);
    
    for (let i = 0; i < allInputs.length; i++) {
      const input = allInputs[i];
      try {
        const type = await input.getAttribute('type');
        const name = await input.getAttribute('name');
        const id = await input.getAttribute('id');
        const placeholder = await input.getAttribute('placeholder');
        const className = await input.getAttribute('class');
        const isVisible = await input.isVisible();
        const isEnabled = await input.isEnabled();
        
        console.log(`  Input ${i + 1}: type="${type}", name="${name}", id="${id}", placeholder="${placeholder}", class="${className}", visible=${isVisible}, enabled=${isEnabled}`);
      } catch (e) {
        console.log(`  Input ${i + 1}: Error getting attributes - ${e.message}`);
      }
    }
    
    // Check for buttons that might trigger login form
    console.log('🔘 Looking for login buttons or triggers...');
    const buttonSelectors = [
      'button',
      '[role="button"]',
      'a[href*="signin"]',
      'a[href*="login"]',
      '.signin',
      '.login',
      '[data-name*="login"]',
      '[data-name*="signin"]'
    ];
    
    for (const selector of buttonSelectors) {
      try {
        const buttons = await page.locator(selector).all();
        for (let i = 0; i < buttons.length; i++) {
          const button = buttons[i];
          try {
            const text = await button.textContent();
            const isVisible = await button.isVisible();
            if (isVisible && text && (text.toLowerCase().includes('sign') || text.toLowerCase().includes('log'))) {
              console.log(`  Found potential login button: "${text}" with selector ${selector}`);
            }
          } catch (e) {
            // Continue
          }
        }
      } catch (e) {
        // Continue
      }
    }
    
    // Look for any clickable elements that might show the login form
    console.log('🎯 Looking for elements that might trigger login form...');
    const clickableSelectors = [
      '[data-qa*="login"]',
      '[data-qa*="signin"]',
      '[data-testid*="login"]',
      '[data-testid*="signin"]',
      '.js-signin',
      '.js-login'
    ];
    
    for (const selector of clickableSelectors) {
      try {
        const element = await page.locator(selector).first();
        if (await element.isVisible()) {
          const text = await element.textContent();
          console.log(`  Found clickable element: "${text}" with selector ${selector}`);
        }
      } catch (e) {
        // Continue
      }
    }
    
    // Check the page content for any hidden forms or components
    console.log('📄 Checking page content for hidden login forms...');
    const pageContent = await page.content();
    const hasLoginKeywords = pageContent.toLowerCase().includes('email') || 
                           pageContent.toLowerCase().includes('password') ||
                           pageContent.toLowerCase().includes('username');
    console.log(`📝 Page contains login keywords: ${hasLoginKeywords}`);
    
    if (pageContent.toLowerCase().includes('email')) {
      console.log('📧 Page contains "email" text');
    }
    if (pageContent.toLowerCase().includes('password')) {
      console.log('🔒 Page contains "password" text');
    }
    
    // Wait for user interaction
    console.log('\n🎮 Browser is open for manual inspection. Press Ctrl+C to close when done.');
    console.log('💡 Look for:');
    console.log('   - Any buttons or links that show the login form');
    console.log('   - Login form that appears after clicking something');
    console.log('   - Network requests that load login form content');
    console.log('   - JavaScript errors in the console');
    
    // Keep the browser open for manual inspection
    await page.waitForTimeout(300000); // Wait 5 minutes
    
  } catch (error) {
    console.error('❌ Error during debug:', error);
    await page.screenshot({ path: './debug-tradingview-error-v2.png', fullPage: true });
  } finally {
    console.log('🔚 Closing browser...');
    await browser.close();
  }
}

// Handle Ctrl+C to close gracefully
process.on('SIGINT', () => {
  console.log('\n👋 Received SIGINT, closing browser...');
  process.exit(0);
});

debugTradingViewLoginV2().catch(console.error);
