/**
 * Test script to verify the "Add New Announcement" button functionality
 * 
 * This script tests the complete workflow:
 * 1. Navigate to master trainer announcements page
 * 2. Verify the "Add New Announcement" button exists
 * 3. Click the button and verify the modal opens
 * 4. Check that all expected form fields are present
 * 5. Verify the form can be closed properly
 */

const { chromium } = require('playwright');

async function testAnnouncementButtonFix() {
    console.log('🔧 Testing "Add New Announcement" button fix...\n');

    const browser = await chromium.launch({ 
        headless: process.env.HEADLESS !== 'false',
        slowMo: 500 // Add delay to see actions
    });

    try {
        const context = await browser.newContext();
        const page = await context.newPage();

        // Test configuration
        const baseUrl = process.env.BASE_URL || 'https://upskillhvac.com';
        const testUsername = 'testuser1'; // Master trainer test user
        const testPassword = 'TestUser123!';

        console.log(`📍 Testing on: ${baseUrl}`);

        // Step 1: Navigate to login page
        console.log('🔐 Logging in as master trainer...');
        await page.goto(`${baseUrl}/training-login/`);
        await page.fill('#user_login', testUsername);
        await page.fill('#user_pass', testPassword);
        await page.click('#wp-submit');
        await page.waitForLoadState('networkidle');

        // Step 2: Navigate to master trainer announcements page
        console.log('📍 Navigating to announcements page...');
        await page.goto(`${baseUrl}/master-trainer/master-announcements/`);
        await page.waitForLoadState('networkidle');

        // Step 3: Verify page loads correctly
        const pageTitle = await page.locator('h1.page-title').textContent();
        console.log(`📄 Page title: "${pageTitle}"`);

        // Step 4: Check if "Add New Announcement" button exists
        const addButton = page.locator('.hvac-add-announcement');
        const buttonExists = await addButton.count() > 0;
        console.log(`🔘 Add button exists: ${buttonExists ? '✅' : '❌'}`);

        if (!buttonExists) {
            throw new Error('Add New Announcement button not found!');
        }

        // Step 5: Check if modal HTML exists in the page
        const modal = page.locator('#announcement-modal');
        const modalExists = await modal.count() > 0;
        console.log(`🗂️ Modal exists: ${modalExists ? '✅' : '❌'}`);

        if (!modalExists) {
            throw new Error('Announcement modal not found in the page!');
        }

        // Step 6: Verify modal is initially hidden
        const modalVisible = await modal.isVisible();
        console.log(`👁️ Modal initially hidden: ${!modalVisible ? '✅' : '❌'}`);

        // Step 7: Check if JavaScript is loaded
        const jqueryLoaded = await page.evaluate(() => {
            return typeof jQuery !== 'undefined';
        });
        console.log(`📜 jQuery loaded: ${jqueryLoaded ? '✅' : '❌'}`);

        const hvacScriptLoaded = await page.evaluate(() => {
            return typeof hvac_announcements !== 'undefined';
        });
        console.log(`📜 HVAC script loaded: ${hvacScriptLoaded ? '✅' : '❌'}`);

        // Step 8: Click the "Add New Announcement" button
        console.log('🖱️ Clicking "Add New Announcement" button...');
        await addButton.click();

        // Step 9: Wait for modal to become visible
        try {
            await page.waitForSelector('#announcement-modal:visible', { timeout: 5000 });
            console.log('✅ Modal opened successfully!');
        } catch (error) {
            console.log('❌ Modal did not open - checking for errors...');
            
            // Check console errors
            const consoleMessages = [];
            page.on('console', msg => consoleMessages.push(msg.text()));
            
            // Wait a bit to capture any delayed errors
            await page.waitForTimeout(2000);
            
            if (consoleMessages.length > 0) {
                console.log('🔍 Console messages:');
                consoleMessages.forEach(msg => console.log(`  - ${msg}`));
            }
            
            throw new Error('Modal failed to open after clicking button');
        }

        // Step 10: Verify form fields are present
        console.log('🔍 Checking form fields...');
        
        const expectedFields = [
            '#announcement-title',
            '#announcement-content_ifr', // TinyMCE iframe
            '#announcement-excerpt',
            '#announcement-status',
            '#announcement-date',
            '#categories-container',
            '#announcement-tags',
            '#featured-image-id'
        ];

        for (const fieldSelector of expectedFields) {
            const field = page.locator(fieldSelector);
            const fieldExists = await field.count() > 0;
            const fieldName = fieldSelector.replace('#', '').replace('_ifr', '');
            console.log(`  📝 ${fieldName}: ${fieldExists ? '✅' : '❌'}`);
        }

        // Step 11: Test modal close functionality
        console.log('🔒 Testing modal close...');
        await page.click('.modal-close');
        await page.waitForSelector('#announcement-modal:not(:visible)', { timeout: 3000 });
        console.log('✅ Modal closes successfully!');

        // Step 12: Test opening modal again to ensure repeatability
        console.log('🔄 Testing modal reopen...');
        await addButton.click();
        await page.waitForSelector('#announcement-modal:visible', { timeout: 3000 });
        console.log('✅ Modal reopens successfully!');

        // Step 13: Test cancel button
        console.log('❌ Testing cancel button...');
        await page.click('.modal-cancel');
        await page.waitForSelector('#announcement-modal:not(:visible)', { timeout: 3000 });
        console.log('✅ Cancel button works!');

        console.log('\n🎉 All tests passed! The "Add New Announcement" button is now working correctly.');
        console.log('\n📋 Summary:');
        console.log('   ✅ Button exists and is clickable');
        console.log('   ✅ Modal HTML is properly rendered');
        console.log('   ✅ JavaScript is loaded and functional');
        console.log('   ✅ Modal opens when button is clicked');
        console.log('   ✅ All form fields are present');
        console.log('   ✅ Modal can be closed properly');
        console.log('   ✅ Functionality is repeatable');

    } catch (error) {
        console.error('❌ Test failed:', error.message);
        process.exit(1);
    } finally {
        await browser.close();
    }
}

// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Promise Rejection:', reason);
    process.exit(1);
});

// Run the test
testAnnouncementButtonFix();