const { test, expect } = require('@playwright/test');

test.describe('JavaScript Execution Debug', () => {
  test('Check if JavaScript is running in calendar page', async ({ page }) => {
    // Navigate to the calendar page
    await page.goto('http://localhost:3000/calendar');
    await page.waitForLoadState('networkidle');
    
    // Check if our custom scripts are loaded
    const jsTests = await page.evaluate(() => {
      // Check if initThemeToggle function exists
      const hasInitThemeToggle = typeof window.initThemeToggle === 'function';
      
      // Check if initStickyHeader function exists  
      const hasInitStickyHeader = typeof window.initStickyHeader === 'function';
      
      // Check if we can access the theme toggle element
      const themeToggle = document.getElementById('theme-toggle');
      const toggleExists = !!themeToggle;
      
      // Check if there are any JavaScript errors on the page
      const hasErrors = window.errors || [];
      
      return {
        hasInitThemeToggle,
        hasInitStickyHeader,
        toggleExists,
        hasErrors: hasErrors.length > 0,
        documentReady: document.readyState,
        domLoaded: !!document.body
      };
    });
    
    console.log('JavaScript execution status:', jsTests);
    
    // Check console messages
    page.on('console', msg => console.log('CONSOLE:', msg.text()));
    page.on('pageerror', error => console.log('PAGE ERROR:', error.message));
    
    // Try manually calling the init function
    const manualInit = await page.evaluate(() => {
      try {
        // Try to manually create and run the theme toggle
        const themeToggle = document.getElementById('theme-toggle');
        if (!themeToggle) return { error: 'No theme toggle element' };
        
        const html = document.documentElement;
        
        // Add event listener manually
        themeToggle.addEventListener('click', () => {
          const currentTheme = html.getAttribute('data-theme');
          const newTheme = currentTheme === 'light' ? 'dark' : 'light';
          html.setAttribute('data-theme', newTheme);
          localStorage.setItem('theme', newTheme);
        });
        
        return { success: true, listenerAdded: true };
      } catch (error) {
        return { error: error.message };
      }
    });
    
    console.log('Manual init result:', manualInit);
    
    // Now try clicking after manual init
    if (manualInit.success) {
      const themeToggle = page.locator('#theme-toggle');
      await themeToggle.click();
      await page.waitForTimeout(500);
      
      const themeAfterManualClick = await page.locator('html').getAttribute('data-theme');
      console.log('Theme after manual click:', themeAfterManualClick);
    }
  });
});