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

/**
 * Communication Templates E2E Tests
 * 
 * Tests the email template management system for trainers
 */

test.describe('Communication Templates Tests', () => {

  test('Templates page loads and displays correctly', async ({ authenticatedPage: page }) => {
    test.setTimeout(25000);
    const actions = new CommonActions(page);

    // Navigate to communication templates page
    await actions.navigateAndWait('/communication-templates/');
    await actions.screenshot('templates-page-loaded');

    // Check page title and heading
    await expect(page.locator('h1')).toContainText('Communication Templates');
    
    // Verify main elements are present
    await expect(page.locator('.hvac-templates-wrapper')).toBeVisible();
    await expect(page.locator('.hvac-templates-header')).toBeVisible();

    console.log('✓ Communication Templates page loaded successfully');
  });

  test('Template manager widget displays in email attendees page', async ({ authenticatedPage: page }) => {
    test.setTimeout(30000);
    const actions = new CommonActions(page);

    // First navigate to dashboard to get an event
    await actions.navigateAndWait('/hvac-dashboard/');
    await actions.screenshot('dashboard-for-event-selection');

    // Look for events with attendees
    const eventLinks = page.locator('a[href*="email-attendees"]');
    const eventCount = await eventLinks.count();

    if (eventCount > 0) {
      // Navigate to email attendees page for first event
      await eventLinks.first().click();
      await page.waitForLoadState('networkidle');
      await actions.screenshot('email-attendees-page-loaded');

      // Check that template manager widget is present
      await expect(page.locator('.hvac-template-manager')).toBeVisible();
      await expect(page.locator('.hvac-template-toggle')).toBeVisible();

      // Check toggle functionality
      const templateToggle = page.locator('.hvac-template-toggle');
      await templateToggle.click();
      await actions.screenshot('template-manager-opened');

      // Template manager should now be visible
      await expect(page.locator('.hvac-template-manager')).toBeVisible();

      console.log('✓ Template manager widget working in email attendees page');
    } else {
      console.log('⚠ No events with email functionality found - skipping widget test');
    }
  });

  test('Template creation functionality works', async ({ authenticatedPage: page }) => {
    test.setTimeout(30000);
    const actions = new CommonActions(page);

    // Navigate to templates page
    await actions.navigateAndWait('/communication-templates/');
    await actions.screenshot('templates-page-for-creation');

    // Look for create template button
    const createButton = page.locator('button:has-text("Create New Template")');
    
    if (await createButton.isVisible()) {
      await createButton.click();
      await actions.screenshot('template-form-opened');

      // Check form elements are present
      await expect(page.locator('#hvac_template_title')).toBeVisible();
      await expect(page.locator('#hvac_template_content')).toBeVisible();
      await expect(page.locator('#hvac_template_category')).toBeVisible();

      // Check placeholder helper is present
      await expect(page.locator('.hvac-placeholder-helper')).toBeVisible();
      await expect(page.locator('.hvac-placeholder-grid')).toBeVisible();

      console.log('✓ Template creation form displays correctly');
    } else {
      console.log('⚠ Template creation interface not found - may need default templates');
    }
  });

  test('Default templates installation works for new trainers', async ({ authenticatedPage: page }) => {
    test.setTimeout(25000);
    const actions = new CommonActions(page);

    // Navigate to templates page
    await actions.navigateAndWait('/communication-templates/');
    await actions.screenshot('templates-page-new-user');

    // Check if this shows getting started section (for users without templates)
    const gettingStarted = page.locator('.hvac-getting-started');
    
    if (await gettingStarted.isVisible()) {
      // New trainer setup detected
      await expect(gettingStarted).toContainText('Welcome to Communication Templates');
      
      // Check for install defaults button
      const installButton = page.locator('a:has-text("Install Default Templates")');
      await expect(installButton).toBeVisible();

      console.log('✓ Getting started interface displays for new trainers');
    } else {
      // User already has templates
      const templatesGrid = page.locator('.hvac-templates-grid');
      if (await templatesGrid.isVisible()) {
        // Check template cards exist
        const templateCards = page.locator('.hvac-template-card');
        const cardCount = await templateCards.count();
        
        expect(cardCount).toBeGreaterThan(0);
        
        // Check template card structure
        await expect(templateCards.first().locator('.hvac-template-card-title')).toBeVisible();
        await expect(templateCards.first().locator('.hvac-template-card-actions')).toBeVisible();

        console.log(`✓ Templates display correctly (${cardCount} templates found)`);
      } else {
        console.log('⚠ No templates found and no getting started section');
      }
    }
  });

  test('Template placeholders system works', async ({ authenticatedPage: page }) => {
    test.setTimeout(20000);
    const actions = new CommonActions(page);

    // Navigate to templates page
    await actions.navigateAndWait('/communication-templates/');
    await actions.screenshot('templates-page-placeholders');

    // Try to open template form to see placeholders
    const createButton = page.locator('button:has-text("Create New Template")');
    
    if (await createButton.isVisible()) {
      await createButton.click();
      await page.waitForTimeout(1000);
      
      // Check placeholder helper is loaded
      const placeholderHelper = page.locator('.hvac-placeholder-helper');
      await expect(placeholderHelper).toBeVisible();

      // Check for some common placeholders
      await expect(page.locator('.hvac-placeholder-item:has-text("{attendee_name}")')).toBeVisible();
      await expect(page.locator('.hvac-placeholder-item:has-text("{event_title}")')).toBeVisible();
      await expect(page.locator('.hvac-placeholder-item:has-text("{trainer_name}")')).toBeVisible();

      console.log('✓ Template placeholders system working correctly');
    } else {
      console.log('⚠ Cannot test placeholders - template form not accessible');
    }
  });

  test('JavaScript functionality loads without errors', async ({ authenticatedPage: page }) => {
    test.setTimeout(20000);
    const actions = new CommonActions(page);

    // Monitor console errors
    const jsErrors: string[] = [];
    page.on('console', (msg) => {
      if (msg.type() === 'error') {
        jsErrors.push(msg.text());
      }
    });

    // Navigate to templates page
    await actions.navigateAndWait('/communication-templates/');
    await actions.screenshot('templates-page-js-check');

    // Check that HVACTemplates object is available
    const hvacTemplatesExists = await page.evaluate(() => {
      return typeof window.HVACTemplates !== 'undefined';
    });

    if (hvacTemplatesExists) {
      console.log('✓ HVACTemplates JavaScript object loaded correctly');
    } else {
      console.log('⚠ HVACTemplates JavaScript object not found');
    }

    // Check for critical JS errors
    const criticalErrors = jsErrors.filter(error => 
      error.includes('HVACTemplates') || 
      error.includes('communication-templates') ||
      error.includes('Uncaught')
    );

    expect(criticalErrors.length).toBe(0);
    console.log(`✓ No critical JavaScript errors found (${jsErrors.length} total console messages)`);
  });

});