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

test('Debug button click handler', 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 what happens when we click the button
  const buttonTest = await page.evaluate(() => {
    const button = document.querySelector('button:has-text("Create New Template")');
    if (!button) return { error: 'Button not found' };

    const onclick = button.getAttribute('onclick');
    return {
      buttonFound: true,
      onclickAttribute: onclick,
      hasOnclickFunction: typeof HVACTemplates.createNewTemplate === 'function'
    };
  });

  console.log('Button investigation:', buttonTest);

  // Try to call the function manually and see what happens
  const manualCall = await page.evaluate(() => {
    try {
      console.log('Calling HVACTemplates.createNewTemplate...');
      HVACTemplates.createNewTemplate();
      
      const overlay = document.getElementById('template-form-overlay');
      return {
        success: true,
        overlayExists: !!overlay,
        display: overlay ? overlay.style.display : 'no overlay'
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  });

  console.log('Manual function call result:', manualCall);

  // Monitor console messages during button click
  const consoleMessages: string[] = [];
  page.on('console', (msg) => {
    consoleMessages.push(`[${msg.type()}] ${msg.text()}`);
  });

  // Click the button and see what happens
  await page.locator('button:has-text("Create New Template")').click();
  await page.waitForTimeout(2000);

  console.log('Console messages after button click:', consoleMessages);

  // Check if modal is visible
  const modalVisible = await page.locator('#template-form-overlay').isVisible();
  console.log('Modal visible after button click:', modalVisible);

  await actions.screenshot('debug-button-click-result');
});