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

/**
 * Basic certificate functionality tests
 * Simplified and robust approach for certificate testing
 * @tag @certificates @basic
 */

test.describe('Certificate Basic Functionality', () => {
  test('Certificate Reports page loads and displays statistics', async ({ authenticatedPage: page }) => {
    const actions = new CommonActions(page);
    
    // Navigate to Certificate Reports
    await actions.navigateAndWait('/certificate-reports/');
    await actions.screenshot('certificate-reports-loaded');
    
    // Verify page loaded correctly
    await expect(page.locator('h1, h2').filter({ hasText: /certificate/i }).first()).toBeVisible();
    
    // Verify navigation is present
    await actions.verifyNavigation();
    
    // Check for statistics (flexible approach)
    const statElements = page.locator('.stat-value, .stat-number, .dashboard-stat');
    const statCount = await statElements.count();
    
    if (statCount > 0) {
      console.log(`Found ${statCount} certificate statistics`);
      
      // Verify at least some statistics are numbers
      for (let i = 0; i < Math.min(statCount, 3); i++) {
        const statText = await statElements.nth(i).textContent();
        const hasNumber = /\d/.test(statText || '');
        expect(hasNumber).toBeTruthy();
      }
    } else {
      console.log('No statistics found - this may be expected');
    }
    
    await actions.screenshot('certificate-reports-verified');
  });

  test('Generate Certificates page loads and shows event selection', async ({ authenticatedPage: page }) => {
    const actions = new CommonActions(page);
    
    // Navigate to Generate Certificates page
    await actions.navigateAndWait('/generate-certificates/');
    await actions.screenshot('generate-certificates-loaded');
    
    // Verify page loaded correctly
    await expect(page.locator('h1, h2').filter({ hasText: /generate.*certificate/i }).first()).toBeVisible();
    
    // Verify navigation is present
    await actions.verifyNavigation();
    
    // Check for event selection
    const eventSelect = page.locator('select[name="event_id"], select[id*="event"]');
    await expect(eventSelect.first()).toBeVisible();
    
    // Check event options
    const eventOptions = await eventSelect.first().locator('option').count();
    expect(eventOptions).toBeGreaterThan(0);
    
    console.log(`Found ${eventOptions} event options (including default)`);
    
    // If there are events, test AJAX loading (but don't submit)
    if (eventOptions > 1) {
      await eventSelect.first().selectOption({ index: 1 });
      await actions.waitForAjax();
      
      // Give time for AJAX to complete
      await page.waitForTimeout(2000);
      
      // Look for any form elements that might have loaded
      const formElements = await page.locator('input[type="checkbox"], input[type="submit"], button[type="submit"]').count();
      console.log(`Found ${formElements} form elements after event selection`);
      
      await actions.screenshot('event-selected');
    }
  });

  test('Certificate navigation between pages works', async ({ authenticatedPage: page }) => {
    const actions = new CommonActions(page);
    
    // Test navigation flow: Reports -> Generate -> Reports
    await actions.navigateAndWait('/certificate-reports/');
    await expect(page.locator('h1, h2').filter({ hasText: /certificate.*report/i })).toBeVisible();
    
    // Click to Generate Certificates
    await page.click('text=Generate Certificates');
    await actions.waitForAjax();
    await expect(page.locator('h1, h2').filter({ hasText: /generate.*certificate/i })).toBeVisible();
    
    // Return to reports via navigation
    await page.click('text=Certificate Reports');
    await actions.waitForAjax();
    await expect(page.locator('h1, h2').filter({ hasText: /certificate.*report/i })).toBeVisible();
    
    // Return to dashboard
    await page.click('a[href*="hvac-dashboard"]');
    await actions.waitForAjax();
    await expect(page).toHaveURL(/hvac-dashboard/);
    
    await actions.screenshot('certificate-navigation-complete');
  });

  test('Certificate pages have no PHP 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 certificate pages for PHP errors
    const certificatePages = [
      '/certificate-reports/',
      '/generate-certificates/'
    ];
    
    for (const certPage of certificatePages) {
      await actions.navigateAndWait(certPage);
      
      // Verify page loaded without errors
      const hasContent = await page.locator('h1, h2, .content, main').count() > 0;
      expect(hasContent).toBeTruthy();
      
      // Wait a moment for any delayed errors
      await page.waitForTimeout(1000);
    }
    
    // Verify no PHP errors occurred
    expect(phpErrors.length).toBe(0);
    console.log('Certificate pages tested - no PHP errors found');
    
    await actions.screenshot('certificate-pages-error-free');
  });
});