import { test, expect } from '@playwright/test';
import { LoginPage } from './LoginPage';
import { DashboardPage } from './DashboardPage';
import { CreateEventPage } from './CreateEventPage';
import { TEST_USERS } from '../data/test-users';
import { TEST_EVENTS } from '../data/test-events';

test.describe('Create Event with TinyMCE Iframe', () => {
    test('Create event using iframe interaction', async ({ page }) => {
        const loginPage = new LoginPage(page);
        const dashboardPage = new DashboardPage(page);
        const createEventPage = new CreateEventPage(page);
        const trainer = TEST_USERS.trainer;
        
        // Login
        await loginPage.navigateToLogin();
        await loginPage.login(trainer.username, trainer.password);
        
        // Navigate to create event
        await dashboardPage.clickCreateEvent();
        
        // Wait for form to load
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(3000);
        
        // Fill event title
        await page.fill('input[name="post_title"]', 'HVAC Fundamentals Training');
        
        // Handle TinyMCE editor - try to find the iframe
        try {
            // Option 1: Direct frame interaction
            const frame = page.frame({ url: /about:blank|javascript:/ });
            if (frame) {
                await frame.locator('body').click();
                await frame.locator('body').fill('Learn the basics of HVAC systems in this comprehensive training session.');
                console.log('Filled description using frame interaction');
            }
        } catch (e) {
            console.log('Frame interaction failed:', e.message);
        }
        
        // Option 2: Try alternative ways to interact with TinyMCE
        if (!await page.locator('body').locator(':has-text("Learn the basics")').isVisible()) {
            try {
                // Try using iframe locator
                const iframeLocator = page.frameLocator('iframe#content_ifr, iframe[id$="_ifr"]');
                const iframeBody = iframeLocator.locator('body');
                await iframeBody.click();
                await iframeBody.fill('Learn the basics of HVAC systems in this comprehensive training session.');
                console.log('Filled description using iframe locator');
            } catch (e) {
                console.log('Iframe locator failed:', e.message);
                
                // Option 3: Try JavaScript injection
                await page.evaluate(() => {
                    const editor = (window as any).tinyMCE?.activeEditor;
                    if (editor) {
                        editor.setContent('Learn the basics of HVAC systems in this comprehensive training session.');
                        console.log('Set content using TinyMCE API');
                    }
                });
            }
        }
        
        // Fill dates
        await page.fill('#EventStartDate', '6/1/2025');
        await page.fill('#EventEndDate', '6/1/2025');
        
        // Fill times
        await page.fill('#EventStartTime', '09:00');
        await page.fill('#EventEndTime', '17:00');
        
        // Submit the form
        await page.click('input[value="Submit Event"]');
        
        // Wait for response
        await page.waitForLoadState('networkidle');
        await page.waitForTimeout(3000);
        
        console.log(`Final URL: ${page.url()}`);
        
        // Take screenshot
        await page.screenshot({ path: 'create-event-iframe-result.png', fullPage: true });
        
        // Check for success
        const pageContent = await page.content();
        if (pageContent.includes('Event Submitted') || pageContent.includes('Event Created')) {
            console.log('Event created successfully!');
        } else if (pageContent.includes('required')) {
            console.log('Form validation error - required fields missing');
        }
    });
});