import { test, expect, chromium } from '@playwright/test';

async function runTest() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    ignoreHTTPSErrors: true,
  });
  const page = await context.newPage();
  
  page.on('console', msg => console.log('BROWSER:', msg.text()));
  
  try {
    await page.goto('https://code-dev.g4dge7.com:5174/sign-in', {
      ignoreHTTPSErrors: true,
    });
    await page.waitForLoadState('networkidle');
    
    console.log('Filling form...');
    await page.fill('#email', 'rob@digitaltelepresence.com');
    await page.fill('#password', 'ionfrali');
    
    // Also evaluate directly in page context to see what's happening
    await page.evaluate(() => {
      console.log('Testing fetch directly...');
      fetch('/auth/sign-in', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          email: 'rob@digitaltelepresence.com',
          password: 'ionfrali'
        })
      }).then(r => r.json()).then(d => {
        console.log('Direct fetch result:', JSON.stringify(d));
      });
    });
    
    console.log('Clicking submit...');
    await page.click('button[type="submit"]');
    
    // Wait and check
    await page.waitForTimeout(3000);
    
    const userData = await page.evaluate(() => localStorage.getItem('dtp_user'));
    const tokenData = await page.evaluate(() => localStorage.getItem('dtp_auth_token'));
    
    console.log('=== RESULTS ===');
    console.log('User in localStorage:', userData ? 'YES' : 'NO');
    console.log('Token in localStorage:', tokenData ? 'YES' : 'NO');
    
    const content = await page.content();
    const welcomeVisible = content.includes('Welcome');
    console.log('Welcome visible:', welcomeVisible);
    
    if (welcomeVisible) {
      console.log('\n✅ PASSED');
    } else {
      console.log('\n❌ FAILED');
    }
    
  } catch (e) {
    console.error('Error:', e.message);
  } finally {
    await browser.close();
  }
}

runTest();