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

async function debugLoginStructure() {
  console.log('🚀 Starting login structure debug...');
  
  const browser = await chromium.launch({
    headless: true,
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage',
      '--disable-blink-features=AutomationControlled',
      '--disable-features=VizDisplayCompositor'
    ]
  });
  
  const context = await browser.newContext({
    viewport: { width: 1920, height: 1080 },
    userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.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: 'domcontentloaded', 
      timeout: 30000 
    });
    
    console.log('⏳ Waiting for page to settle...');
    await page.waitForTimeout(5000);
    
    const currentUrl = await page.url();
    console.log('📍 Current URL:', currentUrl);
    
    // Take screenshot
    await page.screenshot({ path: 'screenshots/debug_login_structure.png', fullPage: true });
    console.log('📸 Screenshot saved to screenshots/debug_login_structure.png');
    
    // Check for email-related buttons/elements
    console.log('🔍 Analyzing page structure...');
    
    const loginElements = await page.evaluate(() => {
      const results = {
        buttons: [],
        inputs: [],
        forms: [],
        links: []
      };
      
      // Find all buttons
      const buttons = Array.from(document.querySelectorAll('button'));
      results.buttons = buttons.map(btn => ({
        text: btn.textContent?.trim() || '',
        className: btn.className,
        id: btn.id,
        type: btn.type || '',
        visible: btn.offsetParent !== null
      })).filter(btn => btn.text.length > 0 || btn.className.length > 0);
      
      // Find all inputs
      const inputs = Array.from(document.querySelectorAll('input'));
      results.inputs = inputs.map(input => ({
        type: input.type,
        name: input.name || '',
        placeholder: input.placeholder || '',
        id: input.id || '',
        className: input.className,
        visible: input.offsetParent !== null
      }));
      
      // Find all forms
      const forms = Array.from(document.querySelectorAll('form'));
      results.forms = forms.map((form, index) => ({
        index,
        action: form.action || '',
        method: form.method || '',
        className: form.className,
        id: form.id || '',
        inputs: Array.from(form.querySelectorAll('input')).length
      }));
      
      // Find all links that might be relevant
      const links = Array.from(document.querySelectorAll('a'));
      results.links = links.map(link => ({
        text: link.textContent?.trim() || '',
        href: link.href || '',
        className: link.className
      })).filter(link => 
        link.text.toLowerCase().includes('email') ||
        link.text.toLowerCase().includes('sign') ||
        link.text.toLowerCase().includes('login') ||
        link.href.includes('signin') ||
        link.href.includes('login')
      );
      
      return results;
    });
    
    console.log('\n📊 LOGIN PAGE ANALYSIS:');
    console.log('=======================');
    
    console.log('\n🔘 BUTTONS:');
    loginElements.buttons.forEach((btn, i) => {
      console.log(`  ${i + 1}. "${btn.text}" (class: ${btn.className}) (visible: ${btn.visible})`);
    });
    
    console.log('\n📝 INPUTS:');
    loginElements.inputs.forEach((input, i) => {
      console.log(`  ${i + 1}. type="${input.type}" name="${input.name}" placeholder="${input.placeholder}" (visible: ${input.visible})`);
    });
    
    console.log('\n📋 FORMS:');
    loginElements.forms.forEach((form, i) => {
      console.log(`  ${i + 1}. action="${form.action}" method="${form.method}" inputs=${form.inputs}`);
    });
    
    console.log('\n🔗 RELEVANT LINKS:');
    loginElements.links.forEach((link, i) => {
      console.log(`  ${i + 1}. "${link.text}" -> ${link.href}`);
    });
    
    // Look specifically for email-related elements
    console.log('\n🔍 EMAIL-SPECIFIC ELEMENTS:');
    const emailElements = await page.evaluate(() => {
      const allElements = document.querySelectorAll('*');
      const emailRelated = [];
      
      for (const el of allElements) {
        const text = el.textContent?.toLowerCase() || '';
        const className = el.className || '';
        const id = el.id || '';
        
        if (text.includes('email') || text.includes('continue with email') || 
            className.includes('email') || id.includes('email')) {
          emailRelated.push({
            tagName: el.tagName,
            text: el.textContent?.trim() || '',
            className: className,
            id: id,
            visible: el.offsetParent !== null
          });
        }
      }
      
      return emailRelated;
    });
    
    emailElements.forEach((el, i) => {
      console.log(`  ${i + 1}. <${el.tagName}> "${el.text}" (class: ${el.className}) (visible: ${el.visible})`);
    });
    
  } catch (error) {
    console.error('❌ Error during debug:', error);
  } finally {
    await browser.close();
  }
}

debugLoginStructure().catch(console.error);
