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

const BASE_URL = 'https://upskill-staging.measurequick.com';

async function testTECTemplateOverride() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ 
    viewport: { width: 1920, height: 1080 },
    ignoreHTTPSErrors: true 
  });
  const page = await context.newPage();
  
  // Set longer default timeout
  page.setDefaultTimeout(60000);
  
  console.log('🧪 Testing TEC Template Override System - Phase 1 Prototype\n');
  console.log('='.repeat(50));
  
  const results = {
    passed: 0,
    failed: 0,
    tests: []
  };
  
  function logTest(name, passed, details = '') {
    const status = passed ? '✅ PASS' : '❌ FAIL';
    console.log(`${status} ${name}`);
    if (details) console.log(`   ${details}`);
    results.tests.push({ name, passed, details });
    if (passed) results.passed++;
    else results.failed++;
  }
  
  try {
    // Step 1: Login as trainer
    console.log('\n🔐 Authenticating as test trainer');
    console.log('-'.repeat(30));
    
    await page.goto(`${BASE_URL}/training-login/`);
    await page.waitForLoadState('networkidle');
    
    // Check if login form is visible
    const usernameField = await page.locator('#username').count();
    const passwordField = await page.locator('#password').count();
    
    if (usernameField === 0 || passwordField === 0) {
      console.log('  Login form not found, trying alternative selectors...');
      await page.screenshot({ path: 'test-results/login-page-debug.png', fullPage: true });
      
      // Try alternative login field selectors based on the screenshot
      const altSelectors = [
        { user: 'input[type="text"]', pass: 'input[type="password"]' },
        { user: '#user_login', pass: '#user_pass' },
        { user: 'input[name="log"]', pass: 'input[name="pwd"]' }
      ];
      
      let loginFound = false;
      for (const selectors of altSelectors) {
        if (await page.locator(selectors.user).count() > 0) {
          await page.fill(selectors.user, 'test_trainer');
          await page.fill(selectors.pass, 'TestTrainer123!');
          loginFound = true;
          console.log(`  ✓ Using login selectors: ${selectors.user} / ${selectors.pass}`);
          break;
        }
      }
      
      if (!loginFound) {
        logTest('Login form found', false, 'Unable to locate login form fields');
        await browser.close();
        return;
      }
    } else {
      await page.fill('#username', 'test_trainer');
      await page.fill('#password', 'TestTrainer123!');
      console.log('  ✓ Using standard login selectors');
    }
    
    // Try multiple submit button selectors
    const submitSelectors = [
      'button[type="submit"]',
      'input[type="submit"]', 
      'button:has-text("Login")',
      'button:has-text("Sign In")',
      '.wp-element-button'
    ];
    
    let submitClicked = false;
    for (const selector of submitSelectors) {
      if (await page.locator(selector).count() > 0) {
        await page.click(selector);
        submitClicked = true;
        console.log(`  ✓ Clicked submit button: ${selector}`);
        break;
      }
    }
    
    if (!submitClicked) {
      logTest('Login submission', false, 'Unable to locate submit button');
      await page.screenshot({ path: 'test-results/submit-button-debug.png', fullPage: true });
      await browser.close();
      return;
    }
    
    await page.waitForURL('**/trainer/dashboard/**', { timeout: 15000 });
    logTest('Trainer login successful', true, 'Authenticated and redirected to dashboard');
    
    // Step 2: Find Community Events form
    console.log('\n🔍 Locating TEC Community Events form');
    console.log('-'.repeat(40));
    
    let eventFormFound = false;
    let eventFormUrl = null;
    
    // Try to find community event form through various methods
    const searchUrls = [
      `${BASE_URL}/community/add/`,
      `${BASE_URL}/events/community/add/`,
      `${BASE_URL}/community/events/add/`,
      `${BASE_URL}/tribe-events/community/add/`,
      `${BASE_URL}/events/add/`,
      `${BASE_URL}/add-event/`
    ];
    
    for (const url of searchUrls) {
      try {
        console.log(`  Checking: ${url}`);
        await page.goto(url, { waitUntil: 'networkidle', timeout: 10000 });
        
        // Check if this is a TEC community event form
        const isTECForm = await page.locator('form[data-datepicker_format]').count() > 0;
        const hasEventTitle = await page.locator('input[name="post_title"]').count() > 0;
        const hasEventDesc = await page.locator('#tcepostcontent, textarea[name="tcepostcontent"]').count() > 0;
        
        if (isTECForm || (hasEventTitle && hasEventDesc)) {
          eventFormFound = true;
          eventFormUrl = url;
          console.log(`  ✓ Found TEC Community Event form at: ${url}`);
          break;
        }
      } catch (error) {
        console.log(`  - URL not accessible: ${url}`);
        continue;
      }
    }
    
    // If no direct access, try through dashboard navigation
    if (!eventFormFound) {
      console.log('  Searching for event creation links in dashboard...');
      await page.goto(`${BASE_URL}/trainer/dashboard/`);
      
      const eventLinks = [
        'text=Create Event',
        'text=Add Event', 
        'text=Submit Event',
        'text=New Event',
        'a[href*="community"]',
        'a[href*="event"]',
        'a[href*="add"]'
      ];
      
      for (const linkSelector of eventLinks) {
        try {
          const link = await page.locator(linkSelector).first();
          if (await link.count() > 0) {
            const href = await link.getAttribute('href');
            console.log(`  ✓ Found potential event link: ${linkSelector} -> ${href}`);
            
            await link.click();
            await page.waitForTimeout(3000);
            
            const isTECForm = await page.locator('form[data-datepicker_format]').count() > 0;
            if (isTECForm) {
              eventFormFound = true;
              eventFormUrl = page.url();
              console.log(`  ✓ Found TEC Community Event form at: ${eventFormUrl}`);
              break;
            }
          }
        } catch (error) {
          continue;
        }
      }
    }
    
    logTest('TEC Community Event form found', eventFormFound, eventFormUrl || 'Form not accessible');
    
    if (!eventFormFound) {
      console.log('\n❌ Unable to locate TEC Community Events form');
      console.log('This could mean:');
      console.log('  - Community Events plugin is not active');
      console.log('  - User permissions insufficient');
      console.log('  - Plugin configuration incomplete');
      console.log('  - URLs have changed');
      
      // Take a screenshot of the current page for debugging
      await page.screenshot({ path: 'test-results/tec-form-not-found-debug.png', fullPage: true });
      
      await browser.close();
      return;
    }
    
    // Step 3: Test Template Override Indicators
    console.log('\n📋 Testing Template Override System');
    console.log('-'.repeat(35));
    
    // TEST 1: Look for our prototype indicator
    const prototypeIndicator = await page.locator('.hvac-prototype-indicator').count() > 0;
    logTest('Template override indicator present', prototypeIndicator, 
            prototypeIndicator ? 'HVAC template override is active' : 'Default TEC template is being used');
    
    if (prototypeIndicator) {
      const indicatorText = await page.locator('.hvac-prototype-indicator').textContent();
      const hasCorrectText = indicatorText.includes('HVAC Template Override Active');
      logTest('Prototype indicator text correct', hasCorrectText, indicatorText.substring(0, 100));
    }
    
    // TEST 2: Check for custom excerpt field
    const excerptField = await page.locator('#hvac_post_excerpt').count() > 0;
    logTest('Custom excerpt field present', excerptField, 
            excerptField ? 'Excerpt field successfully added' : 'Excerpt field not found');
    
    if (excerptField) {
      const excerptLabel = await page.locator('text=Event Excerpt').count() > 0;
      const excerptDesc = await page.locator('text=Brief summary of the event').count() > 0;
      
      logTest('Excerpt field properly labeled', excerptLabel);
      logTest('Excerpt field has description', excerptDesc);
      
      // Test field functionality
      const testExcerpt = 'HVAC TEC Template Override Test - Phase 1 Validation';
      await page.fill('#hvac_post_excerpt', testExcerpt);
      
      const excerptValue = await page.inputValue('#hvac_post_excerpt');
      const excerptFunctional = excerptValue === testExcerpt;
      logTest('Excerpt field accepts input', excerptFunctional, 
              excerptFunctional ? 'Field input/output working correctly' : 'Field input/output failed');
    }
    
    // TEST 3: Verify original TEC form elements still present
    console.log('\n🔧 Testing TEC Form Preservation');
    console.log('-'.repeat(32));
    
    const originalElements = [
      { selector: 'input[name="post_title"]', name: 'Event Title Field' },
      { selector: '#tcepostcontent, textarea[name="tcepostcontent"]', name: 'Event Description Field' },
      { selector: 'form[data-datepicker_format]', name: 'TEC Form Container' },
      { selector: '.tribe-section-header, .tribe-fieldset', name: 'TEC Form Sections' }
    ];
    
    for (const element of originalElements) {
      const exists = await page.locator(element.selector).count() > 0;
      logTest(`${element.name} preserved`, exists, 
              exists ? 'Original TEC element found' : 'Original TEC element missing');
    }
    
    // TEST 4: Test basic form interaction
    console.log('\n📝 Testing Form Interaction');
    console.log('-'.repeat(25));
    
    try {
      // Fill out event title
      const eventTitle = `TEC Template Override Test - ${new Date().getTime()}`;
      await page.fill('input[name="post_title"]', eventTitle);
      
      const titleValue = await page.inputValue('input[name="post_title"]');
      logTest('Event title input working', titleValue === eventTitle);
      
      // Try to fill description (handle both textarea and TinyMCE)
      const descriptionSelectors = ['#tcepostcontent', 'textarea[name="tcepostcontent"]'];
      let descriptionFilled = false;
      
      for (const selector of descriptionSelectors) {
        if (await page.locator(selector).count() > 0) {
          await page.fill(selector, 'This is a test event description for TEC template override validation.');
          descriptionFilled = true;
          break;
        }
      }
      
      logTest('Event description input working', descriptionFilled);
      
      // Verify excerpt field still has our test data
      if (excerptField) {
        const currentExcerpt = await page.inputValue('#hvac_post_excerpt');
        const excerptPersisted = currentExcerpt.includes('HVAC TEC Template Override');
        logTest('Excerpt field data persisted', excerptPersisted, 
                'Field maintains data during form interaction');
      }
      
    } catch (error) {
      logTest('Form interaction test', false, `Error during form interaction: ${error.message}`);
    }
    
    // TEST 5: Check for JavaScript errors
    console.log('\n🚫 Testing Error Handling');
    console.log('-'.repeat(23));
    
    const errors = [];
    page.on('pageerror', error => errors.push(error));
    page.on('console', msg => {
      if (msg.type() === 'error') {
        errors.push(msg.text());
      }
    });
    
    await page.waitForTimeout(3000);
    
    const criticalErrors = errors.filter(error => 
      error.toString().toLowerCase().includes('fatal') ||
      error.toString().toLowerCase().includes('syntax error') ||
      error.toString().toLowerCase().includes('undefined function')
    );
    
    logTest('No critical JavaScript errors', criticalErrors.length === 0,
            criticalErrors.length > 0 ? `${criticalErrors.length} critical errors found` : 'Page loads without critical errors');
    
    // Take final screenshot
    await page.screenshot({ 
      path: 'test-results/tec-template-override-final-state.png', 
      fullPage: true 
    });
    
    console.log('\n📸 Screenshots saved to test-results/');
    
  } catch (error) {
    logTest('Test execution', false, `Fatal error: ${error.message}`);
    await page.screenshot({ path: 'test-results/tec-template-override-error.png', fullPage: true });
  }
  
  await browser.close();
  
  // Summary Report
  console.log('\n' + '='.repeat(60));
  console.log('🎉 TEC TEMPLATE OVERRIDE - PHASE 1 TEST SUMMARY');
  console.log('='.repeat(60));
  console.log(`Total Tests: ${results.passed + results.failed}`);
  console.log(`✅ Passed: ${results.passed}`);
  console.log(`❌ Failed: ${results.failed}`);
  console.log(`Success Rate: ${Math.round((results.passed / (results.passed + results.failed)) * 100)}%`);
  
  if (results.failed === 0) {
    console.log('\n🎊 ALL TESTS PASSED!');
    console.log('✅ Template override system is working correctly');
    console.log('✅ Custom excerpt field successfully added');
    console.log('✅ Original TEC functionality preserved');
    console.log('✅ Foundation established for Phase 2 implementation');
    console.log('\n📋 READY FOR PHASE 2: Complete field implementation');
  } else {
    console.log('\n⚠️  SOME TESTS FAILED');
    console.log('Review the failed tests above and fix issues before proceeding to Phase 2');
    
    console.log('\nFailed Tests:');
    results.tests.filter(t => !t.passed).forEach(t => {
      console.log(`  ❌ ${t.name}: ${t.details}`);
    });
  }
  
  console.log('\n📝 Next Steps:');
  console.log('  1. Review test results and screenshots');
  console.log('  2. Fix any identified issues');
  console.log('  3. Proceed to Phase 2: Complete TEC field implementation');
  console.log('  4. Add remaining WordPress core fields (categories, featured images, etc.)');
  
  return results.passed === (results.passed + results.failed);
}

// Run the test
testTECTemplateOverride().then(success => {
  process.exit(success ? 0 : 1);
}).catch(error => {
  console.error('Test suite failed:', error);
  process.exit(1);
});