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

/**
 * Basic trainer journey functionality tests
 * Simplified and robust approach for trainer workflow testing
 * @tag @trainer-journey @basic
 */

test.describe('Trainer Journey Basic Functionality', () => {
  test('Dashboard loads and shows trainer data', async ({ authenticatedPage: page }) => {
    const actions = new CommonActions(page);
    
    // Verify dashboard access
    await expect(page).toHaveURL(/hvac-dashboard/);
    await actions.screenshot('dashboard-loaded');
    
    // Verify page content
    await expect(page.locator('h1, h2').filter({ hasText: /dashboard/i })).toBeVisible();
    
    // Verify navigation is present
    await actions.verifyNavigation();
    
    // Look for any dashboard content
    const dashboardElements = page.locator('.dashboard-stat, .event-list, table, .stats, .summary');
    const elementCount = await dashboardElements.count();
    
    console.log(`Found ${elementCount} dashboard elements`);
    
    await actions.screenshot('dashboard-verified');
  });

  test('Create Event page loads and displays form', async ({ authenticatedPage: page }) => {
    const actions = new CommonActions(page);
    
    // Navigate to Create Event page
    await actions.navigateAndWait('/manage-event/');
    await actions.screenshot('create-event-loaded');
    
    // Verify page loaded correctly (handle multiple headings)
    await expect(page.locator('h1, h2').filter({ hasText: /create.*event|manage.*event|event/i }).first()).toBeVisible();
    
    // Verify navigation is present
    await actions.verifyNavigation();
    
    // Look for form fields
    const titleField = page.locator('#event_title, #post_title, input[name*="title"]');
    await expect(titleField.first()).toBeVisible();
    
    // Look for description field
    const descriptionFields = page.locator('#event_content, #content, textarea, iframe[id*="_ifr"]');
    const descCount = await descriptionFields.count();
    expect(descCount).toBeGreaterThan(0);
    
    // Look for date fields
    const dateFields = page.locator('input[name*="Date"], input[type="date"]');
    const dateCount = await dateFields.count();
    
    console.log(`Found title field, ${descCount} description fields, ${dateCount} date fields`);
    
    await actions.screenshot('create-event-form-verified');
  });

  test('Event form accepts basic input without submission', async ({ authenticatedPage: page }) => {
    const actions = new CommonActions(page);
    
    // Navigate to Create Event page
    await actions.navigateAndWait('/manage-event/');
    
    // Fill title field
    const titleField = page.locator('#event_title, #post_title, input[name*="title"]').first();
    await titleField.fill('Test Event Title');
    
    // Verify title was filled
    const titleValue = await titleField.inputValue();
    expect(titleValue).toBe('Test Event Title');
    
    // Try to fill description (flexible approach)
    try {
      // Try TinyMCE first
      const frame = page.frameLocator('iframe[id*="_ifr"]');
      await frame.locator('body').fill('Test event description');
      console.log('Filled TinyMCE description');
    } catch {
      // Try textarea alternatives
      const descriptionSelectors = [
        '#event_content',
        '#content',
        'textarea[name*="content"]',
        'textarea'
      ];
      
      let filled = false;
      for (const selector of descriptionSelectors) {
        const field = page.locator(selector);
        if (await field.count() > 0) {
          await field.first().fill('Test event description');
          filled = true;
          console.log(`Filled description using ${selector}`);
          break;
        }
      }
      
      if (!filled) {
        console.log('Could not find description field - this may be expected');
      }
    }
    
    // Don't submit - just verify form accepts input
    console.log('Event form input test completed successfully');
    await actions.screenshot('event-form-input-test');
  });

  test('Profile page loads and displays user information', async ({ authenticatedPage: page }) => {
    const actions = new CommonActions(page);
    
    // Navigate to Profile page
    await actions.navigateAndWait('/community-profile/');
    await actions.screenshot('profile-loaded');
    
    // Verify page loaded correctly
    await expect(page.locator('h1, h2').filter({ hasText: /profile/i })).toBeVisible();
    
    // Verify navigation is present
    await actions.verifyNavigation();
    
    // Look for profile sections
    const profileSections = [
      page.locator('text=Personal'),
      page.locator('text=Business'),
      page.locator('text=Training'),
      page.locator('text=Statistics')
    ];
    
    let visibleSections = 0;
    for (const section of profileSections) {
      if (await section.count() > 0) {
        visibleSections++;
      }
    }
    
    console.log(`Found ${visibleSections} profile sections`);
    expect(visibleSections).toBeGreaterThan(0);
    
    await actions.screenshot('profile-verified');
  });

  test('All main pages load without errors', async ({ authenticatedPage: page }) => {
    const actions = new CommonActions(page);
    const phpErrors = [];
    
    // Monitor for PHP errors
    page.on('console', (msg) => {
      if (msg.type() === 'error' && msg.text().includes('PHP')) {
        phpErrors.push(msg.text());
      }
    });
    
    // Test main trainer pages
    const trainerPages = [
      { path: '/hvac-dashboard/', name: 'Dashboard' },
      { path: '/manage-event/', name: 'Create Event' },
      { path: '/community-profile/', name: 'Profile' },
      { path: '/certificate-reports/', name: 'Certificate Reports' },
      { path: '/generate-certificates/', name: 'Generate Certificates' }
    ];
    
    for (const page_info of trainerPages) {
      console.log(`Testing ${page_info.name}...`);
      await actions.navigateAndWait(page_info.path);
      
      // Verify page loaded
      const hasContent = await page.locator('h1, h2, .content, main').count() > 0;
      expect(hasContent).toBeTruthy();
      
      // Wait for any delayed errors
      await page.waitForTimeout(1000);
      
      await actions.screenshot(`${page_info.name.toLowerCase().replace(/\s+/g, '-')}-tested`);
    }
    
    // Verify no PHP errors occurred
    expect(phpErrors.length).toBe(0);
    console.log('All trainer pages tested - no PHP errors found');
  });
});