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

console.log('🗺️ TRAINER MARKERS 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();
    
    // Monitor console for MapGeo integration logs
    const mapgeoLogs = [];
    page.on('console', msg => {
      const text = msg.text();
      if (text.includes('HVAC MapGeo') || text.includes('MapGeo Safety')) {
        mapgeoLogs.push(text);
        console.log(`   📋 ${text}`);
      }
    });
    
    console.log('🌐 Loading Find a Trainer page...');
    await page.goto(`${BASE_URL}/find-a-trainer/`);
    await page.waitForLoadState('networkidle', { timeout: 20000 });
    
    // Wait for MapGeo integration to process
    console.log('\n⏳ Waiting for MapGeo integration to process...');
    await page.waitForTimeout(10000);
    
    // Check for map elements and markers
    console.log('\n🔍 Checking for map elements...');
    const mapElements = await page.evaluate(() => {
      const elements = {
        fallbackVisible: false,
        mapContainers: document.querySelectorAll('.igmp-map-container, .amcharts-map, #hvac-trainer-map').length,
        amchartsElements: document.querySelectorAll('[id*="amchart"], [class*="amchart"]').length,
        markerElements: document.querySelectorAll('[class*="marker"], [data-trainer]').length,
        interactiveElements: document.querySelectorAll('.igm-clickable, [onclick*="trainer"]').length
      };
      
      const fallback = document.getElementById('hvac-map-fallback');
      if (fallback) {
        const style = window.getComputedStyle(fallback);
        elements.fallbackVisible = style.display !== 'none' && style.visibility !== 'hidden';
        elements.fallbackContent = fallback.textContent || fallback.innerHTML;
      }
      
      return elements;
    });
    
    console.log(`Map containers found: ${mapElements.mapContainers}`);
    console.log(`AmCharts elements: ${mapElements.amchartsElements}`);
    console.log(`Marker elements: ${mapElements.markerElements}`);
    console.log(`Interactive elements: ${mapElements.interactiveElements}`);
    console.log(`Fallback visible: ${mapElements.fallbackVisible}`);
    
    if (mapElements.fallbackVisible) {
      console.log(`Fallback content: "${mapElements.fallbackContent?.substring(0, 100)}..."`);
    }
    
    // Look for PHP error logs that might indicate integration issues
    console.log('\n🔧 Integration analysis...');
    
    const hasCreationLogs = mapgeoLogs.some(log => 
      log.includes('creating from trainer data') || 
      log.includes('Created') && log.includes('trainer markers')
    );
    
    const hasGeocodedTrainers = mapgeoLogs.some(log => 
      log.includes('geocoded trainers')
    );
    
    const hasProcessingLogs = mapgeoLogs.some(log => 
      log.includes('Processing map layout modification')
    );
    
    console.log(`Integration processing: ${hasProcessingLogs ? '✅' : '❌'}`);
    console.log(`Geocoded trainers detected: ${hasGeocodedTrainers ? '✅' : '❌'}`);
    console.log(`Marker creation attempted: ${hasCreationLogs ? '✅' : '❌'}`);
    
    // Summary of all collected logs
    console.log('\n📊 COLLECTED LOGS');
    console.log('================');
    
    if (mapgeoLogs.length > 0) {
      console.log('MapGeo Integration Activity:');
      mapgeoLogs.forEach((log, i) => {
        console.log(`  ${i + 1}. ${log}`);
      });
    } else {
      console.log('❌ No MapGeo integration logs detected');
    }
    
    // Final assessment
    console.log('\n🎯 ASSESSMENT');
    console.log('=============');
    
    const integrationWorking = hasProcessingLogs && (hasCreationLogs || mapElements.markerElements > 0);
    const fallbackWorking = mapElements.fallbackVisible;
    
    console.log(`Integration Status: ${integrationWorking ? '✅ WORKING' : '❌ NEEDS INVESTIGATION'}`);
    console.log(`Safety Fallback: ${fallbackWorking ? '✅ ACTIVE' : '❌ NOT VISIBLE'}`);
    console.log(`Overall Status: ${integrationWorking || fallbackWorking ? '✅ FUNCTIONAL' : '❌ FAILED'}`);

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