import { STAGING_URL, PATHS, TIMEOUTS } from './config/staging-config';
import { test, expect } from '@playwright/test';

test.describe('Final Dashboard Test with Event Creation', () => {
  test('check dashboard displays events after author fix', async ({ page }) => {
    const staging_url = 'https://upskill-staging.measurequick.com';
    
    // Login as test trainer
    await page.goto(`${staging_url}/community-login`);
    await page.fill('#user_login', 'test_trainer');
    await page.fill('#user_pass', 'password123!');
    await page.click('input[type="submit"]');
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(2000);

    // Go to dashboard
    console.log('Navigating to dashboard...');
    await page.goto(`${staging_url}/hvac-dashboard`);
    await page.waitForLoadState('networkidle');
    
    // Take a screenshot for debugging
    await page.screenshot({ path: 'final-dashboard-before.png' });
    
    // Create a new event to test author assignment
    console.log('Creating a new event...');
    await page.goto(`${staging_url}/manage-event`);
    await page.waitForLoadState('networkidle');
    
    // Fill event form
    const eventName = `Author Fix Test Event ${Date.now()}`;
    await page.fill('input[id="title"]', eventName);
    
    // Fill description
    const descriptionField = await page.locator('textarea[id="tcepostcontent"]').isVisible();
    if (descriptionField) {
      await page.fill('textarea[id="tcepostcontent"]', 'Test event created to verify author assignment fix');
    } else {
      // Try iframe
      const iframeExists = await page.locator('#wp-tcepostcontent-editor-container iframe').count() > 0;
      if (iframeExists) {
        const iframe = page.frameLocator('#wp-tcepostcontent-editor-container iframe');
        await iframe.locator('body').fill('Test event created to verify author assignment fix');
      }
    }
    
    // Set date
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dateStr = `${String(tomorrow.getMonth() + 1).padStart(2, '0')}/${String(tomorrow.getDate()).padStart(2, '0')}/${tomorrow.getFullYear()}`;
    await page.fill('#EventStartDate', dateStr);
    await page.fill('#EventEndDate', dateStr);
    
    // Fill venue
    await page.fill('#venue', 'Test Venue - Author Fix');
    await page.fill('#venue-address', '123 Test Street');
    await page.fill('#venue-city', 'Miami');
    await page.selectOption('#venue-state-province', 'FL');
    await page.fill('#venue-zip', '33101');
    
    // Submit
    await page.click('button[type="submit"]');
    console.log('Event submitted, waiting...');
    await page.waitForTimeout(5000);
    
    // Go back to dashboard
    console.log('Returning to dashboard...');
    await page.goto(`${staging_url}/hvac-dashboard`);
    await page.waitForLoadState('networkidle');
    
    // Take screenshot
    await page.screenshot({ path: 'final-dashboard-after.png' });
    
    // Check if the dashboard is loading the custom template
    const content = await page.content();
    
    // Look for specific elements that should be present if the template is loaded
    const hasStatsSection = content.includes('hvac-dashboard-stats') || content.includes('Your Stats');
    const hasStatCards = content.includes('hvac-stat-card') || content.includes('Total Events');
    const hasEventsTable = content.includes('hvac-dashboard-events') || content.includes('Your Events');
    
    console.log('Dashboard Check Results:');
    console.log('Has stats section:', hasStatsSection);
    console.log('Has stat cards:', hasStatCards);
    console.log('Has events table:', hasEventsTable);
    
    // If the template is loading, check the event count
    if (hasStatCards) {
      const totalEventsText = await page.locator('.hvac-stat-card:has-text("Total Events") p').textContent();
      console.log('Total events shown:', totalEventsText);
      const eventCount = parseInt(totalEventsText || '0');
      expect(eventCount).toBeGreaterThan(0);
    } else {
      console.log('Dashboard template not loaded - checking page structure');
      // Log what's actually being displayed
      const titleText = await page.locator('.entry-title').textContent();
      console.log('Page title:', titleText);
      
      // Check if it's using the default page template
      const isDefaultTemplate = content.includes('entry-content clear');
      console.log('Using default template:', isDefaultTemplate);
    }
    
    // Check My Events page to confirm event creation
    await page.goto(`${staging_url}/my-events`);
    await page.waitForLoadState('networkidle');
    
    const eventListed = await page.locator(`text=${eventName}`).count() > 0;
    console.log(`Event "${eventName}" found in My Events:`, eventListed);
    
    // Save full dashboard content for analysis
    const fs = require('fs');
    fs.writeFileSync('final-dashboard-content.html', content);
  });
});