#!/usr/bin/env node

/**
 * Organizer Test with Proper Login Flow
 */

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

const config = {
    BASE_URL: process.env.BASE_URL || 'http://localhost:8080',
    HEADLESS: process.env.HEADLESS !== 'false',
    USERNAME: 'testtrainer',
    PASSWORD: 'TestPass123!'
};

async function testWithLogin() {
    console.log('🧪 Testing Organizer Management with Proper Login');
    console.log('=================================================\n');
    
    const browser = await chromium.launch({ 
        headless: config.HEADLESS,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const page = await browser.newPage();
    
    try {
        // Step 1: Navigate to login page
        console.log('1. Navigating to login page...');
        await page.goto(`${config.BASE_URL}/community-login/`);
        await page.waitForLoadState('networkidle');
        
        // Check if we're already logged in by looking for the form
        const isLoggedIn = await page.locator('#loginform').isHidden();
        
        if (!isLoggedIn) {
            console.log('2. Logging in as trainer...');
            await page.fill('#user_login', config.USERNAME);
            await page.fill('#user_pass', config.PASSWORD);
            await page.click('#wp-submit');
            await page.waitForLoadState('networkidle');
            
            // Check if login was successful
            const currentUrl = page.url();
            console.log(`   Current URL after login: ${currentUrl}`);
            
            if (currentUrl.includes('wp-login.php') || currentUrl.includes('community-login')) {
                console.log('   ❌ Login failed - still on login page');
                const errorMessage = await page.locator('.login-error').textContent().catch(() => '');
                if (errorMessage) {
                    console.log(`   Error: ${errorMessage}`);
                }
                return;
            } else {
                console.log('   ✅ Login successful');
            }
        } else {
            console.log('2. Already logged in, proceeding...');
        }
        
        // Step 3: Test organizer list page
        console.log('\n3. Testing organizer list page...');
        const listResponse = await page.goto(`${config.BASE_URL}/trainer/organizer/list/`);
        await page.waitForLoadState('networkidle');
        
        console.log(`   Status: ${listResponse.status()}`);
        
        if (listResponse.status() === 200) {
            console.log('   ✅ Organizer list page accessible');
            
            const title = await page.title();
            console.log(`   Page title: "${title}"`);
            
            // Check for content
            const content = await page.content();
            const hasShortcode = content.includes('[hvac_trainer_organizers_list]');
            const hasContainer = content.includes('hvac-organizers-list');
            const hasTable = content.includes('hvac-organizers-table');
            
            console.log(`   Has unprocessed shortcode: ${hasShortcode ? 'Yes ❌' : 'No ✅'}`);
            console.log(`   Has organizer container: ${hasContainer ? 'Yes ✅' : 'No ❌'}`);
            console.log(`   Has organizer table: ${hasTable ? 'Yes ✅' : 'No ❌'}`);
            
        } else {
            console.log(`   ❌ Failed with status ${listResponse.status()}`);
        }
        
        // Step 4: Test organizer manage page
        console.log('\n4. Testing organizer manage page...');
        const manageResponse = await page.goto(`${config.BASE_URL}/trainer/organizer/manage/`);
        await page.waitForLoadState('networkidle');
        
        console.log(`   Status: ${manageResponse.status()}`);
        
        if (manageResponse.status() === 200) {
            console.log('   ✅ Organizer manage page accessible');
            
            const title = await page.title();
            console.log(`   Page title: "${title}"`);
            
            // Check for content
            const content = await page.content();
            const hasShortcode = content.includes('[hvac_trainer_organizer_manage]');
            const hasContainer = content.includes('hvac-organizer-manage');
            const hasForm = content.includes('hvac-organizer-form');
            const hasNameField = content.includes('org_name');
            
            console.log(`   Has unprocessed shortcode: ${hasShortcode ? 'Yes ❌' : 'No ✅'}`);
            console.log(`   Has organizer container: ${hasContainer ? 'Yes ✅' : 'No ❌'}`);
            console.log(`   Has organizer form: ${hasForm ? 'Yes ✅' : 'No ❌'}`);
            console.log(`   Has name field: ${hasNameField ? 'Yes ✅' : 'No ❌'}`);
            
            // Try to find the form
            const form = await page.locator('#hvac-organizer-form');
            const formVisible = await form.isVisible();
            console.log(`   Form visible: ${formVisible ? 'Yes ✅' : 'No ❌'}`);
            
            if (formVisible) {
                const fields = ['org_name', 'hq_city', 'hq_state', 'hq_country'];
                for (const field of fields) {
                    const fieldExists = await page.locator(`#${field}`).isVisible();
                    console.log(`   Field ${field}: ${fieldExists ? '✅' : '❌'}`);
                }
            }
            
        } else {
            console.log(`   ❌ Failed with status ${manageResponse.status()}`);
        }
        
        // Step 5: Debug current page source
        console.log('\n5. Debug information...');
        const content = await page.content();
        
        // Look for debug information in the source
        if (content.includes('HVAC_IN_PAGE_TEMPLATE')) {
            console.log('   ✅ Template constant found - using plugin template');
        } else {
            console.log('   ❌ Template constant not found - may not be using plugin template');
        }
        
        // Check for CSS/JS
        const cssLinks = await page.locator('link[href*="hvac"]').count();
        const jsScripts = await page.locator('script[src*="hvac"]').count();
        console.log(`   HVAC CSS files: ${cssLinks}`);
        console.log(`   HVAC JS files: ${jsScripts}`);
        
    } catch (error) {
        console.error(`❌ Test error: ${error.message}`);
    } finally {
        await browser.close();
    }
}

testWithLogin();