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

async function testAuthenticatedPage() {
  const browser = await chromium.launch({ 
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  
  const context = await browser.newContext({
    viewport: { width: 1280, height: 1024 }
  });
  
  const page = await context.newPage();
  
  // Initialize data collection
  const failedRequests = [];
  const consoleErrors = [];
  const networkRequests = [];
  
  // Monitor console messages
  page.on('console', msg => {
    const text = msg.text();
    const type = msg.type();
    
    if (type === 'error' || type === 'warning') {
      consoleErrors.push({
        type: type,
        message: text,
        timestamp: new Date().toISOString()
      });
      console.log(`Console ${type}: ${text}`);
    }
  });
  
  // Monitor page errors
  page.on('pageerror', error => {
    consoleErrors.push({
      type: 'pageerror',
      message: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString()
    });
    console.log('Page error:', error.message);
  });
  
  // Monitor network requests
  page.on('request', request => {
    networkRequests.push({
      url: request.url(),
      method: request.method(),
      headers: request.headers(),
      timestamp: new Date().toISOString()
    });
  });
  
  page.on('response', response => {
    const url = response.url();
    const status = response.status();
    
    // Track all API responses
    if (url.includes('/api/')) {
      console.log(`API Response: ${status} ${url}`);
      
      if (status >= 400) {
        failedRequests.push({
          url: url,
          status: status,
          statusText: response.statusText(),
          timestamp: new Date().toISOString()
        });
      }
    }
  });
  
  try {
    console.log('🔑 Step 1: Authenticating...');
    
    // First, login to establish session
    await page.goto('http://192.168.0.46:3000/login-new');
    await page.waitForTimeout(1000);
    
    // Accept cookies if needed
    const cookieBanner = await page.$('#cookie-consent-banner');
    if (cookieBanner) {
      console.log('Accepting cookies...');
      await page.click('#cookie-accept-btn');
      await page.waitForTimeout(1000);
    }
    
    // Fill login form
    await page.fill('#email', 'tmartinez@gmail.com');
    await page.fill('#password', 'TestPassword123!');
    
    console.log('Submitting login...');
    await page.click('#login-btn');
    
    // Wait for redirect after login
    await page.waitForTimeout(3000);
    
    const postLoginUrl = page.url();
    console.log('Post-login URL:', postLoginUrl);
    
    if (!postLoginUrl.includes('/dashboard') && !postLoginUrl.includes('/events/')) {
      console.error('❌ Login failed, still on login page');
      await page.screenshot({ path: 'debug-login-failed.png' });
      return;
    }
    
    console.log('✅ Authentication successful');
    
    console.log('\n🎯 Step 2: Loading event management page...');
    
    // Navigate to the event management page
    const targetUrl = 'http://192.168.0.46:3000/events/7ac12bd2-8509-4db3-b1bc-98a808646311/manage';
    await page.goto(targetUrl, { 
      waitUntil: 'networkidle',
      timeout: 30000 
    });
    
    console.log('Page loaded, waiting for components to stabilize...');
    
    // Wait for the page to stabilize
    await page.waitForTimeout(5000);
    
    // Check page details
    const pageTitle = await page.title();
    const currentUrl = page.url();
    
    console.log('Final URL:', currentUrl);
    console.log('Page title:', pageTitle);
    
    // Check if we're still on login page
    if (currentUrl.includes('/login')) {
      console.log('❌ Still redirected to login page - authentication not persisting');
      await page.screenshot({ path: 'debug-auth-not-persisting.png' });
      return;
    }
    
    // Check for specific UI components
    const componentChecks = {
      '.stats-block': false,
      '.attendee-list': false,
      '.qr-code-preview': false,
      '[data-testid="event-stats"]': false,
      '[data-testid="ticket-types"]': false,
      '[data-testid="orders-section"]': false,
      '.tab-content': false,
      '.event-management': false,
      '.card': false,
      '.glassmorphism': false,
      'nav': false,
      'main': false,
      'header': false
    };
    
    const missingComponents = [];
    const foundComponents = [];
    
    for (const [selector, _] of Object.entries(componentChecks)) {
      try {
        const element = await page.$(selector);
        if (element) {
          componentChecks[selector] = true;
          foundComponents.push(selector);
          console.log(`✓ Found component: ${selector}`);
        } else {
          missingComponents.push(selector);
          console.log(`✗ Missing component: ${selector}`);
        }
      } catch (error) {
        missingComponents.push(selector);
        console.log(`✗ Error checking component ${selector}:`, error.message);
      }
    }
    
    // Check for authentication state in browser
    const authState = await page.evaluate(() => {
      return {
        hasSupabaseClient: typeof window.supabase !== 'undefined',
        hasAuthUser: window.authUser || null,
        hasOrganizationId: window.organizationId || null,
        cookies: document.cookie,
        localStorage: Object.keys(localStorage).length,
        sessionStorage: Object.keys(sessionStorage).length,
        pathname: window.location.pathname,
        search: window.location.search
      };
    });
    
    console.log('\n🔍 Browser state:', authState);
    
    // Check for visible content on the page
    const pageContent = await page.evaluate(() => {
      const body = document.body;
      const textContent = body.textContent || '';
      
      return {
        hasContent: textContent.length > 100,
        contentPreview: textContent.slice(0, 200) + '...',
        bodyClasses: body.className,
        hasMainElement: !!document.querySelector('main'),
        hasNavElement: !!document.querySelector('nav'),
        hasArticleElement: !!document.querySelector('article'),
        totalElements: document.querySelectorAll('*').length
      };
    });
    
    console.log('\n📄 Page content analysis:', pageContent);
    
    // Take screenshot
    const screenshotDir = path.join(__dirname, 'screenshots');
    if (!fs.existsSync(screenshotDir)) {
      fs.mkdirSync(screenshotDir, { recursive: true });
    }
    
    const screenshotPath = path.join(screenshotDir, 'authenticated-event-manage.png');
    await page.screenshot({ 
      path: screenshotPath, 
      fullPage: true 
    });
    
    console.log(`📸 Screenshot saved to: ${screenshotPath}`);
    
    // Generate diagnostic report
    const report = {
      route: '/events/7ac12bd2-8509-4db3-b1bc-98a808646311/manage',
      status: currentUrl.includes('/login') ? 'auth_failed' : (foundComponents.length > 0 ? 'partial_success' : 'components_missing'),
      timestamp: new Date().toISOString(),
      authentication: {
        loginSuccessful: !currentUrl.includes('/login'),
        sessionPersistent: !currentUrl.includes('/login'),
        finalUrl: currentUrl
      },
      page_info: {
        title: pageTitle,
        url: currentUrl,
        loaded: true
      },
      screenshot: screenshotPath,
      failed_requests: failedRequests,
      missing_components: missingComponents,
      found_components: foundComponents,
      console_errors: consoleErrors,
      auth_state: authState,
      page_content: pageContent,
      network_summary: {
        total_requests: networkRequests.length,
        api_requests: networkRequests.filter(req => req.url.includes('/api/')).length,
        failed_requests: failedRequests.length
      },
      notes: generateNotes(foundComponents, missingComponents, consoleErrors, authState, currentUrl)
    };
    
    // Save detailed report
    const reportPath = path.join(__dirname, 'authenticated-debug-report.json');
    fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
    
    console.log('\n=== AUTHENTICATED DIAGNOSTIC REPORT ===');
    console.log(JSON.stringify(report, null, 2));
    console.log(`\nFull report saved to: ${reportPath}`);
    
    return report;
    
  } catch (error) {
    console.error('Error during authenticated page test:', error);
    
    // Take screenshot even on error
    try {
      const screenshotDir = path.join(__dirname, 'screenshots');
      if (!fs.existsSync(screenshotDir)) {
        fs.mkdirSync(screenshotDir, { recursive: true });
      }
      
      const errorScreenshotPath = path.join(screenshotDir, 'authenticated-error.png');
      await page.screenshot({ 
        path: errorScreenshotPath, 
        fullPage: true 
      });
      
      console.log(`Error screenshot saved to: ${errorScreenshotPath}`);
    } catch (screenshotError) {
      console.error('Failed to take error screenshot:', screenshotError);
    }
    
    return {
      route: '/events/7ac12bd2-8509-4db3-b1bc-98a808646311/manage',
      status: 'error',
      error: error.message,
      failed_requests: failedRequests,
      console_errors: consoleErrors,
      notes: `Critical error during authenticated page test: ${error.message}`
    };
  } finally {
    await browser.close();
  }
}

function generateNotes(foundComponents, missingComponents, consoleErrors, authState, currentUrl) {
  const notes = [];
  
  if (currentUrl.includes('/login')) {
    notes.push('Authentication failed - redirected to login page');
    return notes.join('. ');
  }
  
  if (foundComponents.length > 0) {
    notes.push(`${foundComponents.length} UI components found: ${foundComponents.slice(0, 3).join(', ')}`);
  }
  
  if (missingComponents.length > 0) {
    notes.push(`${missingComponents.length} UI components missing`);
  }
  
  if (consoleErrors.length > 0) {
    notes.push(`${consoleErrors.length} console errors detected`);
  }
  
  if (!authState.hasSupabaseClient) {
    notes.push('Supabase client not initialized on page');
  }
  
  if (foundComponents.length === 0 && missingComponents.length > 5) {
    notes.push('Page may not be rendering properly - no expected components found');
  }
  
  if (notes.length === 0) {
    notes.push('Page loaded successfully with authentication');
  }
  
  return notes.join('. ');
}

// Run the authenticated test
testAuthenticatedPage()
  .then(report => {
    console.log('\n=== AUTHENTICATED TEST COMPLETE ===');
    if (report.status === 'partial_success' || report.status === 'auth_failed') {
      console.log('✅ Authentication working, some components found');
    } else if (report.status === 'components_missing') {
      console.log('⚠️  Authentication working but components missing');
    } else {
      console.log('❌ Issues detected');
    }
    process.exit(report.status === 'error' ? 1 : 0);
  })
  .catch(error => {
    console.error('Fatal error:', error);
    process.exit(1);
  });