import { test, expect } from '@playwright/test';
import { CommonActions } from './utils/common-actions';

/**
 * Master Dashboard test using admin user
 */

test.describe('Master Dashboard Admin Access', () => {
  
  test('Admin user can access Master Dashboard', async ({ page }) => {
    test.setTimeout(60000);
    const actions = new CommonActions(page);
    
    // Navigate to WP login page and login as admin
    await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
    await page.waitForLoadState('networkidle');
    
    // Login as admin_trainer (has administrator role)
    await page.fill('#user_login', 'admin_trainer');
    await page.fill('#user_pass', 'Admin123!');
    await page.click('#wp-submit');
    
    // Wait for login to complete
    await page.waitForLoadState('networkidle');
    
    // Check if login was successful
    const afterLoginUrl = page.url();
    console.log('URL after admin login:', afterLoginUrl);
    
    if (afterLoginUrl.includes('wp-admin')) {
      console.log('✓ Successfully logged in as admin');
      
      // Navigate directly to master dashboard
      await page.goto('https://upskill-staging.measurequick.com/master-dashboard/');
      await page.waitForLoadState('networkidle');
      
      // Take screenshot
      await page.screenshot({ 
        path: `test-results/screenshots/master-dashboard-admin-${Date.now()}.png`,
        fullPage: true 
      });
      
      // Check final URL
      const masterDashUrl = page.url();
      console.log('Master Dashboard URL:', masterDashUrl);
      
      // Check page content
      const pageTitle = await page.title();
      console.log('Page title:', pageTitle);
      
      // Look for dashboard elements
      const h1Count = await page.locator('h1').count();
      console.log('H1 elements found:', h1Count);
      
      if (h1Count > 0) {
        const h1Text = await page.locator('h1').first().textContent();
        console.log('H1 text:', h1Text);
        
        // Check what we see
        if (h1Text?.includes('Master Dashboard')) {
          console.log('✓ Master Dashboard rendered successfully!');
          
          // Look for key elements
          const systemOverview = await page.locator('text=System Overview').count();
          console.log('System Overview found:', systemOverview > 0 ? '✓' : '✗');
          
          const statCards = await page.locator('.hvac-stat-card').count();
          console.log('Number of stat cards:', statCards);
          
          // Look for specific statistics
          const stats = [
            'Total Events',
            'Upcoming Events',
            'Completed Events',
            'Active Trainers',
            'Tickets Sold',
            'Total Revenue'
          ];
          
          for (const stat of stats) {
            const found = await page.locator(`.hvac-stat-card:has-text("${stat}")`).count();
            console.log(`${stat}:`, found > 0 ? '✓' : '✗');
          }
          
          // Look for trainer analytics section
          const trainerAnalytics = await page.locator('text=Trainer Analytics').count();
          console.log('Trainer Analytics section:', trainerAnalytics > 0 ? '✓' : '✗');
          
          // Look for events table
          const eventsTable = await page.locator('table, .events-table').count();
          console.log('Events table found:', eventsTable > 0 ? '✓' : '✗');
          
          // Success!
          expect(h1Text).toContain('Master Dashboard');
          expect(statCards).toBeGreaterThan(0);
          
        } else if (h1Text?.includes('Access Denied')) {
          console.log('✗ Access Denied - admin does not have permission');
          console.log('This suggests the capability check needs fixing');
        } else {
          console.log('✗ Unexpected page content:', h1Text);
        }
      } else {
        console.log('✗ No H1 elements found - page may not be rendering');
        
        // Check page source for debugging
        const pageContent = await page.content();
        if (pageContent.includes('[hvac_master_dashboard]')) {
          console.log('✗ Shortcode found unprocessed in page source');
        }
        if (pageContent.includes('Trainer Login')) {
          console.log('✗ Redirected to login page');
        }
      }
    } else {
      console.log('✗ Admin login failed');
      console.log('Login error or unexpected redirect');
    }
  });
});