import { test, expect } from './fixtures/auth';
import { CommonActions } from './utils/common-actions';

/**
 * TEC Shortcode Processing Check
 * 
 * This test verifies that The Events Calendar Community Events shortcode
 * is being processed correctly on the manage-event page.
 */
test.describe('TEC Shortcode Processing', () => {
  test('Verify TEC shortcode is processed on manage-event page', async ({ authenticatedPage: page }) => {
    test.setTimeout(30000);
    const actions = new CommonActions(page);

    // Navigate to Create Event page
    await actions.navigateAndWait('/manage-event/');
    await actions.screenshot('tec-shortcode-page-loaded');
    
    // Wait for the page to be fully loaded
    await page.waitForLoadState('networkidle');
    
    // Get page content
    const pageContent = await page.locator('body').innerText();
    
    // Check if raw shortcode is visible (which would be bad)
    const hasRawShortcode = pageContent.includes('[tribe_community_events');
    if (hasRawShortcode) {
      console.log('❌ ERROR: TEC shortcode is not being processed!');
      console.log('The page shows the raw shortcode text instead of the form.');
      
      // Check if TEC plugin is active
      console.log('\nDebugging info:');
      console.log('- Page URL:', page.url());
      console.log('- Page title:', await page.title());
      
      // Look for any error messages
      const errors = await page.locator('.error, .notice-error').allTextContents();
      if (errors.length > 0) {
        console.log('- Error messages found:', errors);
      }
      
      // Check if there's any form at all
      const formCount = await page.locator('form').count();
      console.log(`- Forms on page: ${formCount}`);
      
      throw new Error('TEC Community Events shortcode is not being processed');
    }
    
    // Look for expected TEC form elements
    const expectedElements = {
      'Event form': 'form[id*="community"], form[class*="tribe"]',
      'Title field': 'input[name="post_title"], input#post_title',
      'Content area': 'textarea[name="post_content"], iframe[id*="_ifr"]',
      'Date fields': 'input[name*="EventDate"], input[id*="EventDate"]',
      'Submit button': 'input[type="submit"], button[type="submit"]'
    };
    
    console.log('✅ TEC shortcode is being processed (no raw shortcode found)');
    console.log('\nChecking for expected form elements:');
    
    for (const [name, selector] of Object.entries(expectedElements)) {
      const element = page.locator(selector).first();
      const count = await element.count();
      const isVisible = count > 0 ? await element.isVisible() : false;
      
      console.log(`- ${name}: ${count > 0 ? '✓ Found' : '✗ Not found'} ${isVisible ? '(visible)' : ''}`);
      
      if (count > 0 && name === 'Event form') {
        const formId = await element.getAttribute('id');
        const formClass = await element.getAttribute('class');
        console.log(`  Form details: id="${formId}", class="${formClass}"`);
      }
    }
    
    // Take a screenshot of the form
    await actions.screenshot('tec-form-structure');
    
    // Additional debugging: Check page structure
    const h1 = await page.locator('h1').first().textContent();
    const h2 = await page.locator('h2').first().textContent();
    console.log(`\nPage headings:`);
    console.log(`- H1: ${h1}`);
    console.log(`- H2: ${h2}`);
    
    // Check if we can identify the form type
    const hasTECForm = await page.locator('form[id*="tribe-community-events"], form.tribe-community-events-form').count() > 0;
    const hasHVACForm = await page.locator('form#hvac-event-form').count() > 0;
    
    console.log(`\nForm type detection:`);
    console.log(`- TEC Community form: ${hasTECForm ? 'Yes' : 'No'}`);
    console.log(`- HVAC custom form: ${hasHVACForm ? 'Yes' : 'No'}`);
    
    // Final assertion
    expect(hasRawShortcode).toBe(false);
    expect(await page.locator('form').count()).toBeGreaterThan(0);
  });

  test('Check TEC plugin activation status', async ({ page }) => {
    test.setTimeout(30000);
    const actions = new CommonActions(page);

    // This test creates a temporary script to check plugin status
    console.log('Creating script to check TEC plugin status...');
    
    // Note: This is a conceptual test that would need server access
    // In practice, you might need to check this via wp-cli or admin panel
    
    // Navigate to a page that should have TEC functionality
    await actions.navigateAndWait('/manage-event/');
    
    // Check for plugin-specific classes or attributes
    const tecIndicators = [
      '[class*="tribe-"]',
      '[id*="tribe-"]',
      '[data-plugin="the-events-calendar"]',
      'script[src*="tribe-events"]'
    ];
    
    console.log('Checking for TEC plugin indicators:');
    for (const selector of tecIndicators) {
      const count = await page.locator(selector).count();
      if (count > 0) {
        console.log(`✓ Found TEC indicator: ${selector} (${count} elements)`);
      }
    }
    
    // The test passes if we found some form on the page
    const hasForm = await page.locator('form').count() > 0;
    expect(hasForm).toBe(true);
  });
});