const { chromium } = require('playwright');
const fs = require('fs').promises;

async function takeScreenshot(page, name) {
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  const filename = `screenshots/${name}-${timestamp}.png`;
  try {
    await page.screenshot({ path: filename, fullPage: true });
    console.log(`   📸 Screenshot saved: ${filename}`);
  } catch (e) {
    console.log(`   ⚠️  Could not save screenshot: ${e.message}`);
  }
}

(async () => {
  // Create screenshots directory
  try {
    await fs.mkdir('screenshots', { recursive: true });
  } catch (e) {}

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

  try {
    console.log('=== Testing Custom HVAC Event Creation and Edit Pages ===\n');

    // 1. Login as test_trainer
    console.log('1. Logging in as test_trainer...');
    await page.goto('https://upskill-staging.measurequick.com/training-login/');
    await page.waitForLoadState('networkidle');

    await page.fill('input[name="log"], input[name="username"], input#user_login', 'test_trainer');
    await page.fill('input[name="pwd"], input[name="password"], input#user_pass', 'TestTrainer123!');
    await page.click('input[type="submit"], button[type="submit"]');
    await page.waitForLoadState('networkidle');
    
    console.log('   ✅ Logged in successfully\n');

    // 2. Test Custom Create Event Page (if it exists)
    console.log('2. Testing Custom HVAC Create Event Page...');
    const customCreateUrls = [
      'https://upskill-staging.measurequick.com/trainer/event/create/',
      'https://upskill-staging.measurequick.com/trainer/create-event/',
      'https://upskill-staging.measurequick.com/trainer/event/add/',
      'https://upskill-staging.measurequick.com/trainer/add-event/'
    ];

    let customCreateFound = false;
    for (const url of customCreateUrls) {
      console.log(`   Trying: ${url}`);
      const response = await page.goto(url, { waitUntil: 'networkidle' });
      
      if (response && response.status() === 200) {
        customCreateFound = true;
        console.log(`   ✅ Found custom create page at: ${url}`);
        
        // Check what's on the page
        const pageContent = await page.evaluate(() => {
          const form = document.querySelector('form#create-event-form, form.hvac-event-form, form[action*="event"]');
          const shortcode = document.querySelector('[class*="tribe"], [id*="tribe"]');
          const customForm = document.querySelector('.hvac-create-event, .hvac-event-create');
          
          // Check for specific form fields
          const fields = {
            title: document.querySelector('input[name="event_title"], input[name="post_title"], input#event-title'),
            description: document.querySelector('textarea[name="event_description"], textarea[name="post_content"], textarea#event-description'),
            startDate: document.querySelector('input[name="event_start_date"], input[name="_EventStartDate"], input#event-start-date'),
            endDate: document.querySelector('input[name="event_end_date"], input[name="_EventEndDate"], input#event-end-date'),
            venue: document.querySelector('input[name="event_venue"], select[name="venue"], input#event-venue'),
            organizer: document.querySelector('input[name="event_organizer"], select[name="organizer"], input#event-organizer')
          };
          
          // Check for AJAX/REST API integration
          const hasAjax = !!document.querySelector('script[src*="hvac-event"], script[src*="rest-event"]');
          
          return {
            hasForm: !!form,
            hasShortcode: !!shortcode,
            hasCustomForm: !!customForm,
            hasAjax,
            fields: Object.keys(fields).reduce((acc, key) => {
              acc[key] = !!fields[key];
              return acc;
            }, {}),
            formAction: form ? form.getAttribute('action') : null,
            formMethod: form ? form.getAttribute('method') : null
          };
        });
        
        console.log('   Page Analysis:');
        console.log('     - Has form:', pageContent.hasForm);
        console.log('     - Has TEC shortcode:', pageContent.hasShortcode);
        console.log('     - Has custom HVAC form:', pageContent.hasCustomForm);
        console.log('     - Has AJAX/REST integration:', pageContent.hasAjax);
        console.log('     - Form fields present:');
        Object.entries(pageContent.fields).forEach(([field, present]) => {
          console.log(`       • ${field}: ${present ? '✅' : '❌'}`);
        });
        
        if (pageContent.formAction) {
          console.log('     - Form action:', pageContent.formAction);
          console.log('     - Form method:', pageContent.formMethod);
        }
        
        await takeScreenshot(page, 'custom-create-page');
        break;
      }
    }
    
    if (!customCreateFound) {
      console.log('   ℹ️  No custom HVAC create event page found\n');
    }

    // 3. Test Custom Edit Event Pages
    console.log('\n3. Testing Custom HVAC Edit Event Pages...');
    
    // Try different URL patterns for editing the events we created
    const eventIds = ['6074', '6075', '6076'];
    const editPatterns = [
      'https://upskill-staging.measurequick.com/trainer/event/edit/{id}/',
      'https://upskill-staging.measurequick.com/trainer/edit-event/{id}/',
      'https://upskill-staging.measurequick.com/trainer/event/{id}/edit/',
      'https://upskill-staging.measurequick.com/edit-event/?event_id={id}'
    ];

    let customEditFound = false;
    for (const pattern of editPatterns) {
      const url = pattern.replace('{id}', eventIds[0]);
      console.log(`   Trying: ${url}`);
      
      const response = await page.goto(url, { waitUntil: 'networkidle' });
      
      if (response && response.status() === 200) {
        customEditFound = true;
        console.log(`   ✅ Found custom edit page at: ${url}`);
        
        // Analyze the edit page
        const editPageContent = await page.evaluate(() => {
          const form = document.querySelector('form#edit-event-form, form.hvac-event-form, form[action*="event"]');
          
          // Check if fields are populated
          const fieldValues = {
            title: document.querySelector('input[name="event_title"], input[name="post_title"], input#event-title')?.value,
            description: document.querySelector('textarea[name="event_description"], textarea[name="post_content"], textarea#event-description')?.value,
            startDate: document.querySelector('input[name="event_start_date"], input[name="_EventStartDate"], input#event-start-date')?.value,
            endDate: document.querySelector('input[name="event_end_date"], input[name="_EventEndDate"], input#event-end-date')?.value,
            venue: document.querySelector('input[name="event_venue"], select[name="venue"], input#event-venue')?.value
          };
          
          // Check for hidden fields indicating event ID
          const eventIdField = document.querySelector('input[name="event_id"], input[name="post_ID"], input#event-id');
          
          return {
            hasForm: !!form,
            hasEventId: !!eventIdField,
            eventId: eventIdField?.value,
            fieldValues,
            fieldsPopulated: Object.values(fieldValues).filter(v => v && v.trim()).length
          };
        });
        
        console.log('   Edit Page Analysis:');
        console.log('     - Has form:', editPageContent.hasForm);
        console.log('     - Has event ID field:', editPageContent.hasEventId);
        console.log('     - Event ID:', editPageContent.eventId);
        console.log('     - Fields populated:', editPageContent.fieldsPopulated, 'out of', Object.keys(editPageContent.fieldValues).length);
        console.log('     - Field values:');
        Object.entries(editPageContent.fieldValues).forEach(([field, value]) => {
          const display = value ? (value.length > 50 ? value.substring(0, 50) + '...' : value) : 'empty';
          console.log(`       • ${field}: ${display}`);
        });
        
        await takeScreenshot(page, 'custom-edit-page');
        break;
      }
    }
    
    if (!customEditFound) {
      console.log('   ℹ️  No custom HVAC edit event page found\n');
    }

    // 4. Test the Manage Event Page for Custom Forms
    console.log('\n4. Checking Manage Event Page for Custom Forms...');
    await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
    await page.waitForLoadState('networkidle');

    const managePageAnalysis = await page.evaluate(() => {
      // Check for embedded forms or AJAX functionality
      const embeddedForm = document.querySelector('form#create-event-form, form.hvac-event-form');
      const ajaxScripts = document.querySelectorAll('script[src*="hvac"], script[src*="event"]');
      const shortcodes = document.querySelector('.tribe-community-events, [class*="tribe-community"]');
      
      // Check for custom HVAC event elements
      const customElements = {
        createButton: document.querySelector('.hvac-create-event-btn, button[onclick*="createEvent"]'),
        eventList: document.querySelector('.hvac-events-list, .hvac-my-events'),
        ajaxContainer: document.querySelector('[data-ajax-events], .ajax-event-container')
      };
      
      // Check page content
      const pageText = document.body.textContent;
      const hasHVACReferences = pageText.includes('HVAC') || pageText.includes('hvac');
      const hasTECReferences = pageText.includes('tribe') || pageText.includes('The Events Calendar');
      
      return {
        hasEmbeddedForm: !!embeddedForm,
        ajaxScriptCount: ajaxScripts.length,
        hasShortcode: !!shortcodes,
        customElements: Object.keys(customElements).reduce((acc, key) => {
          acc[key] = !!customElements[key];
          return acc;
        }, {}),
        hasHVACReferences,
        hasTECReferences,
        ajaxScripts: Array.from(ajaxScripts).map(s => s.src).filter(src => src.includes('hvac') || src.includes('event'))
      };
    });

    console.log('   Manage Page Analysis:');
    console.log('     - Has embedded form:', managePageAnalysis.hasEmbeddedForm);
    console.log('     - AJAX scripts:', managePageAnalysis.ajaxScriptCount);
    console.log('     - Has TEC shortcode:', managePageAnalysis.hasShortcode);
    console.log('     - Custom HVAC elements:');
    Object.entries(managePageAnalysis.customElements).forEach(([element, present]) => {
      console.log(`       • ${element}: ${present ? '✅' : '❌'}`);
    });
    console.log('     - Has HVAC references:', managePageAnalysis.hasHVACReferences);
    console.log('     - Has TEC references:', managePageAnalysis.hasTECReferences);
    
    if (managePageAnalysis.ajaxScripts.length > 0) {
      console.log('     - HVAC/Event AJAX scripts loaded:');
      managePageAnalysis.ajaxScripts.forEach(script => {
        console.log(`       • ${script.split('/').pop()}`);
      });
    }

    // 5. Check REST API Endpoints
    console.log('\n5. Testing REST API Event Endpoints...');
    
    // Get nonce for REST API
    const restNonce = await page.evaluate(() => {
      return window.hvac_ajax?.nonce || window.wp?.apiFetch?.nonceMiddleware?.nonce || '';
    });

    if (restNonce) {
      console.log('   Found REST nonce, testing endpoints...');
      
      // Test create endpoint
      const createResponse = await page.evaluate(async (nonce) => {
        try {
          const response = await fetch('/wp-json/hvac/v1/events', {
            method: 'GET',
            headers: {
              'X-WP-Nonce': nonce
            }
          });
          return {
            status: response.status,
            ok: response.ok,
            statusText: response.statusText
          };
        } catch (e) {
          return { error: e.message };
        }
      }, restNonce);
      
      console.log('   GET /wp-json/hvac/v1/events:', 
        createResponse.error ? `Error: ${createResponse.error}` : 
        `${createResponse.status} ${createResponse.statusText}`);
    } else {
      console.log('   ℹ️  No REST API nonce found');
    }

    // 6. Check JavaScript Console for Errors
    console.log('\n6. Checking for JavaScript Errors...');
    
    const consoleMessages = [];
    page.on('console', msg => {
      if (msg.type() === 'error') {
        consoleMessages.push(msg.text());
      }
    });
    
    // Reload manage page to capture any JS errors
    await page.goto('https://upskill-staging.measurequick.com/trainer/event/manage/');
    await page.waitForLoadState('networkidle');
    
    if (consoleMessages.length > 0) {
      console.log('   ⚠️  JavaScript errors found:');
      consoleMessages.forEach(msg => {
        console.log(`     • ${msg}`);
      });
    } else {
      console.log('   ✅ No JavaScript errors detected');
    }

    // 7. Test Form Submission (if custom form exists)
    if (customCreateFound) {
      console.log('\n7. Testing Custom Form Submission...');
      
      // Navigate back to create page
      await page.goto('https://upskill-staging.measurequick.com/trainer/event/create/');
      await page.waitForLoadState('networkidle');
      
      // Try to fill and submit form
      const formTest = await page.evaluate(() => {
        const form = document.querySelector('form#create-event-form, form.hvac-event-form');
        if (!form) return { hasForm: false };
        
        // Fill test data
        const titleField = document.querySelector('input[name="event_title"], input#event-title');
        const descField = document.querySelector('textarea[name="event_description"], textarea#event-description');
        
        if (titleField) titleField.value = 'Test Event from Automation';
        if (descField) descField.value = 'This is a test event created by automation testing.';
        
        // Check submit button
        const submitBtn = form.querySelector('button[type="submit"], input[type="submit"]');
        
        return {
          hasForm: true,
          filledTitle: !!titleField,
          filledDescription: !!descField,
          hasSubmitButton: !!submitBtn,
          submitText: submitBtn?.textContent || submitBtn?.value
        };
      });
      
      console.log('   Form test results:');
      console.log('     - Form found:', formTest.hasForm);
      console.log('     - Filled title:', formTest.filledTitle);
      console.log('     - Filled description:', formTest.filledDescription);
      console.log('     - Has submit button:', formTest.hasSubmitButton);
      console.log('     - Submit button text:', formTest.submitText);
    }

    // Summary
    console.log('\n=== Test Summary ===');
    console.log('Custom HVAC Event System Status:');
    console.log(`  - Custom Create Page: ${customCreateFound ? '✅ Found' : '❌ Not Found'}`);
    console.log(`  - Custom Edit Page: ${customEditFound ? '✅ Found' : '❌ Not Found'}`);
    console.log(`  - REST API Integration: ${restNonce ? '✅ Nonce Present' : '❌ Not Active'}`);
    
    console.log('\nRecommendation:');
    if (!customCreateFound && !customEditFound) {
      console.log('  → Custom HVAC event system appears to be disabled');
      console.log('  → Using TEC Community Events is the correct approach');
    } else {
      console.log('  ⚠️  Custom HVAC event system may still be partially active');
      console.log('  → This could cause conflicts with TEC Community Events');
      console.log('  → Consider fully disabling custom event code');
    }

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