import { test, expect } from './fixtures/auth';
import { CommonActions } from './utils/common-actions';

test('Debug modal visibility', async ({ authenticatedPage: page }) => {
  test.setTimeout(30000);
  const actions = new CommonActions(page);

  // Navigate to templates page
  await actions.navigateAndWait('/communication-templates/');
  
  // Wait for scripts
  await page.waitForFunction(() => typeof HVACTemplates !== 'undefined');

  // Check initial modal state
  const modalInitialState = await page.evaluate(() => {
    const overlay = document.getElementById('template-form-overlay');
    return {
      exists: !!overlay,
      display: overlay ? getComputedStyle(overlay).display : 'not found',
      visibility: overlay ? getComputedStyle(overlay).visibility : 'not found'
    };
  });
  
  console.log('Modal initial state:', modalInitialState);

  // Click create button
  const createButton = page.locator('button:has-text("Create New Template")');
  await expect(createButton).toBeVisible();
  
  console.log('Clicking create button...');
  await createButton.click();
  
  // Wait a moment
  await page.waitForTimeout(2000);

  // Check modal state after click
  const modalAfterClick = await page.evaluate(() => {
    const overlay = document.getElementById('template-form-overlay');
    return {
      exists: !!overlay,
      display: overlay ? getComputedStyle(overlay).display : 'not found',
      visibility: overlay ? getComputedStyle(overlay).visibility : 'not found'
    };
  });
  
  console.log('Modal after click:', modalAfterClick);

  // Try calling the function directly
  const directCall = await page.evaluate(() => {
    if (typeof HVACTemplates !== 'undefined' && HVACTemplates.createNewTemplate) {
      HVACTemplates.createNewTemplate();
      
      const overlay = document.getElementById('template-form-overlay');
      return {
        functionExists: true,
        display: overlay ? getComputedStyle(overlay).display : 'not found'
      };
    }
    return { functionExists: false };
  });
  
  console.log('Direct function call result:', directCall);

  // Take a screenshot
  await actions.screenshot('modal-debug-final');
});