const { chromium } = require('@playwright/test');

(async () => {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext();
  const page = await context.newPage();

  console.log('🔍 Testing HVAC Announcements System on Staging...\n');

  try {
    // Step 1: Login as master trainer
    console.log('1. Logging in as master trainer...');
    await page.goto('https://upskill-staging.measurequick.com/training-login/');
    await page.waitForLoadState('networkidle', { timeout: 15000 });
    
    await page.fill('#user_login', 'test_master');
    await page.fill('#user_pass', 'TestMaster123!');
    await page.click('#wp-submit');
    
    // Wait for redirect after login
    await page.waitForTimeout(3000);
    const currentUrl = page.url();
    console.log(`   ✅ Logged in successfully, current URL: ${currentUrl}`);

    // Step 2: Test master trainer announcements page
    console.log('\n2. Testing master trainer announcements page...');
    await page.goto('https://upskill-staging.measurequick.com/master-trainer/manage-announcements/');
    await page.waitForTimeout(3000);
    
    const pageTitle = await page.title();
    console.log(`   Page title: ${pageTitle}`);
    
    // Check if page loads without 404
    const is404 = await page.locator('h1').textContent().then(text => 
      text && (text.includes('404') || text.includes('Not Found'))
    ).catch(() => false);
    
    if (is404) {
      console.log('   ❌ Page returns 404 - need to create the page');
    } else {
      console.log('   ✅ Page loads successfully');
      
      // Check for announcements content
      const hasShortcode = await page.textContent('body').then(text => 
        text.includes('[hvac_announcements_manager]')
      );
      
      const hasManager = await page.locator('#hvac-announcements-app, .hvac-announcements-manager').count();
      
      console.log(`   Shortcode visible: ${hasShortcode ? 'Yes' : 'No'}`);
      console.log(`   Manager component loaded: ${hasManager > 0 ? 'Yes' : 'No'}`);
    }

    // Step 3: Test trainer announcements page
    console.log('\n3. Testing trainer announcements page...');
    await page.goto('https://upskill-staging.measurequick.com/trainer/announcements/');
    await page.waitForTimeout(3000);
    
    const trainerPageTitle = await page.title();
    console.log(`   Page title: ${trainerPageTitle}`);
    
    const trainerIs404 = await page.locator('h1').textContent().then(text => 
      text && (text.includes('404') || text.includes('Not Found'))
    ).catch(() => false);
    
    if (trainerIs404) {
      console.log('   ❌ Page returns 404 - need to create the page');
    } else {
      console.log('   ✅ Page loads successfully');
      
      const hasTimelineShortcode = await page.textContent('body').then(text => 
        text.includes('[hvac_announcements_timeline]')
      );
      
      const hasTimeline = await page.locator('.hvac-announcements-timeline, .hvac-announcements-list').count();
      
      console.log(`   Timeline shortcode visible: ${hasTimelineShortcode ? 'Yes' : 'No'}`);
      console.log(`   Timeline component loaded: ${hasTimeline > 0 ? 'Yes' : 'No'}`);
    }

    // Step 4: Test training resources page  
    console.log('\n4. Testing training resources page...');
    await page.goto('https://upskill-staging.measurequick.com/trainer/training-resources/');
    await page.waitForTimeout(3000);
    
    const resourcesPageTitle = await page.title();
    console.log(`   Page title: ${resourcesPageTitle}`);
    
    const resourcesIs404 = await page.locator('h1').textContent().then(text => 
      text && (text.includes('404') || text.includes('Not Found'))
    ).catch(() => false);
    
    if (resourcesIs404) {
      console.log('   ❌ Page returns 404 - need to create the page');
    } else {
      console.log('   ✅ Page loads successfully');
      
      const hasGoogleDriveShortcode = await page.textContent('body').then(text => 
        text.includes('[hvac_google_drive_embed')
      );
      
      const hasIframe = await page.locator('iframe').count();
      
      console.log(`   Google Drive shortcode visible: ${hasGoogleDriveShortcode ? 'Yes' : 'No'}`);
      console.log(`   iframe loaded: ${hasIframe > 0 ? 'Yes' : 'No'}`);
    }

    // Step 5: Check if pages exist in WordPress admin
    console.log('\n5. Checking WordPress pages...');
    await page.goto('https://upskill-staging.measurequick.com/wp-admin/edit.php?post_type=page');
    await page.waitForTimeout(3000);
    
    // Search for our pages
    const searchField = await page.locator('#post-search-input');
    if (await searchField.count() > 0) {
      await searchField.fill('announcements');
      await page.click('#search-submit');
      await page.waitForTimeout(2000);
      
      const pageRows = await page.locator('.wp-list-table tbody tr').count();
      console.log(`   Found ${pageRows} pages matching "announcements"`);
      
      if (pageRows > 0) {
        const titles = await page.locator('.wp-list-table .row-title').allTextContents();
        console.log(`   Page titles found: ${titles.join(', ')}`);
      }
    }

    console.log('\n📋 Summary:');
    console.log('- If pages return 404, they need to be created manually in WordPress');
    console.log('- Templates are deployed and ready');
    console.log('- Shortcodes are registered and should work once pages exist');

  } catch (error) {
    console.error('❌ Test failed:', error.message);
  } finally {
    await browser.close();
  }
})();