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

console.log('🔧 FIND A TRAINER MODAL DEBUG');
console.log('============================');

const BASE_URL = process.env.BASE_URL || 'https://upskill-staging.measurequick.com';

(async () => {
  let browser;

  try {
    browser = await chromium.launch({ 
      headless: false, // Keep visible for debugging
      timeout: 30000
    });
    
    const page = await browser.newPage();
    
    console.log('🌐 Loading Find a Trainer page...');
    await page.goto(`${BASE_URL}/find-a-trainer/`);
    await page.waitForLoadState('networkidle', { timeout: 20000 });
    
    // Check initial modal state
    console.log('\n🔍 Initial modal state...');
    const modalExists = await page.locator('#hvac-filter-modal').count();
    console.log(`Modal element exists: ${modalExists > 0}`);
    
    if (modalExists > 0) {
      const modalStyle = await page.locator('#hvac-filter-modal').getAttribute('style');
      console.log(`Modal initial style: ${modalStyle}`);
      
      const computedStyle = await page.locator('#hvac-filter-modal').evaluate(el => {
        const computed = window.getComputedStyle(el);
        return {
          display: computed.display,
          visibility: computed.visibility,
          opacity: computed.opacity
        };
      });
      console.log(`Modal computed styles:`, computedStyle);
    }
    
    // Check filter button and click
    console.log('\n🔘 Testing filter button click...');
    const formatButton = await page.locator('.hvac-filter-btn[data-filter="training_format"]');
    const buttonExists = await formatButton.count();
    console.log(`Training Format button exists: ${buttonExists > 0}`);
    
    if (buttonExists > 0) {
      console.log('🖱️ Clicking Training Format button...');
      await formatButton.click();
      
      // Wait a moment for any AJAX/JS to execute
      await page.waitForTimeout(2000);
      
      // Check modal state after click
      console.log('\n📋 Modal state after click...');
      const modalVisible = await page.locator('#hvac-filter-modal').isVisible();
      console.log(`Modal visible: ${modalVisible}`);
      
      const modalStyleAfter = await page.locator('#hvac-filter-modal').getAttribute('style');
      console.log(`Modal style after click: ${modalStyleAfter}`);
      
      // Check if AJAX was called
      const hasLoading = await formatButton.getAttribute('class');
      console.log(`Button classes after click: ${hasLoading}`);
      
      // Try to manually show the modal for debugging
      console.log('\n🔧 Manual modal display test...');
      await page.locator('#hvac-filter-modal').evaluate(el => {
        el.style.display = 'flex';
        el.style.visibility = 'visible';
        el.style.opacity = '1';
      });
      
      await page.waitForTimeout(1000);
      const manualVisible = await page.locator('#hvac-filter-modal').isVisible();
      console.log(`Modal visible after manual style change: ${manualVisible}`);
      
      // Check if modal content was populated
      const modalTitle = await page.locator('.hvac-filter-modal-title').textContent();
      const optionsCount = await page.locator('.hvac-filter-option').count();
      console.log(`Modal title: "${modalTitle}"`);
      console.log(`Filter options count: ${optionsCount}`);
    }
    
    // Check console logs for errors
    console.log('\n🔍 Checking JavaScript console...');
    page.on('console', msg => {
      console.log(`   JS ${msg.type()}: ${msg.text()}`);
    });
    
    // Check if AJAX endpoint is working
    console.log('\n🔄 Testing AJAX endpoint directly...');
    const ajaxResponse = await page.evaluate(async () => {
      const formData = new FormData();
      formData.append('action', 'hvac_get_filter_options');
      formData.append('filter_type', 'training_format');
      
      try {
        const response = await fetch('/wp-admin/admin-ajax.php', {
          method: 'POST',
          body: formData
        });
        
        const text = await response.text();
        return {
          status: response.status,
          ok: response.ok,
          response: text.substring(0, 200) + '...'
        };
      } catch (e) {
        return { error: e.message };
      }
    });
    
    console.log('AJAX Response:', ajaxResponse);
    
    // Keep browser open for manual inspection
    console.log('\n⏳ Keeping browser open for 30 seconds for manual inspection...');
    await page.waitForTimeout(30000);

  } catch (error) {
    console.error('\n💥 Error:', error.message);
  } finally {
    if (browser) {
      await browser.close();
    }
  }
})();