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

console.log('🗺️ MAP MARKERS FIX VERIFICATION');
console.log('===============================');

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

(async () => {
  let browser;

  try {
    browser = await chromium.launch({ 
      headless: process.env.HEADLESS !== 'false',
      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 for MapGeo safety fallback
    console.log('\n🛡️ Checking MapGeo safety system...');
    const fallbackExists = await page.locator('#hvac-map-fallback').count();
    console.log(`MapGeo fallback container exists: ${fallbackExists > 0}`);
    
    // Check map container
    console.log('\n🗺️ Checking map container...');
    const mapContainer = await page.locator('#hvac-trainer-map, .hvac-map-container, #map, .igmp-map-container').count();
    console.log(`Map containers found: ${mapContainer}`);
    
    // Wait for map initialization
    console.log('\n⏳ Waiting for map initialization (15 seconds)...');
    await page.waitForTimeout(15000);
    
    // Check for map elements after loading
    const mapElements = await page.evaluate(() => {
      const elements = {
        amcharts: document.querySelectorAll('[id*="amchart"], [class*="amchart"]').length,
        interactive: document.querySelectorAll('.igmp-map-container, .igm-map').length,
        fallback: document.getElementById('hvac-map-fallback'),
        fallbackVisible: false
      };
      
      if (elements.fallback) {
        const style = window.getComputedStyle(elements.fallback);
        elements.fallbackVisible = style.display !== 'none' && style.visibility !== 'hidden';
      }
      
      return elements;
    });
    
    console.log(`AmCharts elements found: ${mapElements.amcharts}`);
    console.log(`Interactive map elements found: ${mapElements.interactive}`);
    console.log(`Fallback visible: ${mapElements.fallbackVisible}`);
    
    // Check console for MapGeo safety messages
    console.log('\n🔍 Monitoring console messages...');
    let mapgeSuccessMessages = [];
    let mapgeoErrors = [];
    
    page.on('console', msg => {
      const text = msg.text();
      if (text.includes('[MapGeo Safety]')) {
        if (text.includes('fallback') || text.includes('Map loaded successfully')) {
          mapgeSuccessMessages.push(text);
          console.log(`   ✅ ${text}`);
        } else {
          mapgeoErrors.push(text);
          console.log(`   ⚠️ ${text}`);
        }
      }
    });
    
    // Force a CDN failure simulation if possible
    console.log('\n🔄 Testing CDN failure scenario...');
    try {
      await page.route('**/amcharts.com/**', route => route.abort());
      await page.reload();
      await page.waitForTimeout(10000);
      
      const fallbackAfterBlock = await page.locator('#hvac-map-fallback').isVisible();
      console.log(`Fallback shows after CDN block: ${fallbackAfterBlock}`);
      
    } catch (e) {
      console.log(`CDN blocking test failed: ${e.message}`);
    }
    
    // Final results
    console.log('\n📊 TEST RESULTS');
    console.log('===============');
    
    const success = mapElements.interactive > 0 || mapElements.fallbackVisible;
    console.log(`Map System Status: ${success ? '✅ WORKING' : '❌ FAILED'}`);
    console.log(`Safety System Active: ${fallbackExists > 0 ? '✅ YES' : '❌ NO'}`);
    console.log(`Map Elements Present: ${mapElements.amcharts + mapElements.interactive}`);
    
    if (mapgeSuccessMessages.length > 0) {
      console.log('\n✅ MapGeo Safety Success Messages:');
      mapgeSuccessMessages.forEach(msg => console.log(`   • ${msg}`));
    }
    
    if (mapgeoErrors.length > 0) {
      console.log('\n⚠️ MapGeo Warnings/Errors:');
      mapgeoErrors.forEach(msg => console.log(`   • ${msg}`));
    }

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