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

test('Test button click functionality', async ({ authenticatedPage: page }) => {
  test.setTimeout(30000);
  const actions = new CommonActions(page);

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

  // Navigate to templates page
  await actions.navigateAndWait('/communication-templates/');
  
  // Wait for scripts and override
  await page.waitForFunction(() => typeof HVACTemplates !== 'undefined');
  await page.waitForTimeout(2000); // Give the override time to load

  // Click the Create New Template button
  const createButton = page.locator('button:has-text("Create New Template")');
  await expect(createButton).toBeVisible();
  
  console.log('Clicking Create New Template button...');
  await createButton.click();
  
  // Wait for modal to appear
  await page.waitForTimeout(1000);
  
  // Check if modal is visible
  const modalVisible = await page.locator('#template-form-overlay').isVisible();
  console.log('Modal visible after button click:', modalVisible);

  // If modal is visible, interact with it
  if (modalVisible) {
    await expect(page.locator('#hvac_template_title')).toBeVisible();
    await page.fill('#hvac_template_title', 'Button Click Test Template');
    await page.fill('#hvac_template_content', 'This template was created by clicking the button!');
    await page.selectOption('#hvac_template_category', 'general');
    
    await actions.screenshot('button-click-modal-filled');
    console.log('Successfully filled modal form via button click');
  } else {
    await actions.screenshot('button-click-no-modal');
    console.log('Modal did not appear after button click');
  }

  // Log console messages
  console.log('Console messages:', consoleMessages.slice(-10)); // Last 10 messages
});