import { test, expect } from '@playwright/test';
import { STAGING_CONFIG } from '../../playwright.config';

test.describe('Event Creation with Test Trainer', () => {
  test('should create community event as trainer', async ({ page }) => {
    // Login as test_trainer
    await page.goto(`https://${STAGING_CONFIG.url}/wp-login.php`);
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'Test123!');
    await page.click('#wp-submit');
    
    // Wait for navigation
    await page.waitForTimeout(3000);
    
    // Check if we're logged in
    const currentUrl = page.url();
    console.log('Current URL after login:', currentUrl);
    
    // Navigate to community events page
    await page.goto(`https://${STAGING_CONFIG.url}/community/add`);
    
    // Wait for form to load
    await page.waitForSelector('#post_title', { timeout: 10000 });
    
    // Fill basic event details
    const title = `HVAC Test Event ${Date.now()}`;
    await page.fill('#post_title', title);
    console.log('Filled title:', title);
    
    // Try different ways to fill description
    // Method 1: Direct textarea fill
    const textareas = await page.locator('textarea').all();
    console.log(`Found ${textareas.length} textareas`);
    
    for (let i = 0; i < textareas.length; i++) {
      const name = await textareas[i].getAttribute('name');
      const id = await textareas[i].getAttribute('id');
      console.log(`Textarea ${i}: name="${name}" id="${id}"`);
      
      if (name === 'tcepostcontent' || id === 'tcepostcontent') {
        await textareas[i].fill('Test event description for trainer submission');
        console.log('Filled description in textarea');
      }
    }
    
    // Method 2: JavaScript fill
    await page.evaluate(() => {
      const textarea = document.querySelector('textarea[name="tcepostcontent"], #tcepostcontent');
      if (textarea) {
        textarea.value = 'Test event description for trainer submission';
        textarea.dispatchEvent(new Event('change', { bubbles: true }));
        console.log('Filled via JavaScript');
      }
    });
    
    // Method 3: Try text mode
    const textTab = await page.locator('.wp-switch-editor.switch-text, #tcepostcontent-tmce').first();
    if (await textTab.isVisible()) {
      await textTab.click();
      await page.waitForTimeout(500);
      
      const textArea = page.locator('#tcepostcontent').first();
      await textArea.fill('Test event description for trainer submission');
      console.log('Filled via text mode');
    }
    
    // Set dates
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dateStr = tomorrow.toISOString().split('T')[0];
    
    await page.fill('#EventStartDate', dateStr);
    await page.fill('#EventEndDate', dateStr);
    await page.fill('#EventStartTime', '10:00 AM');
    await page.fill('#EventEndTime', '12:00 PM');
    console.log('Filled dates');
    
    // Monitor console for errors
    page.on('console', msg => {
      if (msg.type() === 'error') {
        console.error('Console error:', msg.text());
      }
      if (msg.text().includes('required')) {
        console.log('Validation message:', msg.text());
      }
    });
    
    // Submit form
    const submitButton = page.locator('input[type="submit"][name="community-event"]').first();
    const beforeSubmitUrl = page.url();
    
    await submitButton.click();
    console.log('Clicked submit button');
    
    // Wait for response
    await page.waitForTimeout(5000);
    
    // Check result
    const afterSubmitUrl = page.url();
    const hasNavigated = beforeSubmitUrl !== afterSubmitUrl;
    const hasSuccess = await page.locator('.tribe-success-msg, .success').isVisible().catch(() => false);
    const hasErrors = await page.locator('.tribe-error, .error').isVisible().catch(() => false);
    
    console.log('Before URL:', beforeSubmitUrl);
    console.log('After URL:', afterSubmitUrl);
    console.log('Navigated:', hasNavigated);
    console.log('Has success:', hasSuccess);
    console.log('Has errors:', hasErrors);
    
    // Get any error messages
    if (hasErrors) {
      const errorTexts = await page.locator('.tribe-error, .error').allTextContents();
      console.log('Error messages:', errorTexts);
    }
    
    // Assert navigation or success
    expect(hasNavigated || hasSuccess).toBeTruthy();
  });
});