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

const screenshotsDir = path.join(__dirname, 'test-screenshots');
if (!fs.existsSync(screenshotsDir)) {
  fs.mkdirSync(screenshotsDir, { recursive: true });
}

let screenshotCount = 0;

async function takeScreenshot(page, name) {
  screenshotCount++;
  const num = screenshotCount.toString().padStart(2, '0');
  const filename = num + '-' + name + '.png';
  const filepath = path.join(screenshotsDir, filename);
  await page.screenshot({ path: filepath, fullPage: true });
  console.log('Screenshot saved: ' + filename);
  return filepath;
}

async function runTest() {
  let browser;
  try {
    console.log('Starting Playwright test...');
    
    browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    console.log('Step 1: Navigate to application');
    await page.goto('http://localhost:3000', { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(2000);
    await takeScreenshot(page, '01-initial-page');
    console.log('Page loaded');
    
    console.log('Step 2: Looking for menu...');
    const buttons = await page.locator('button').all();
    console.log('Found ' + buttons.length + ' buttons');
    
    for (let btn of buttons) {
      const txt = await btn.textContent();
      console.log('  Button: ' + txt);
    }
    
    await takeScreenshot(page, '02-initial-buttons');
    
    console.log('Test completed');
    
    await context.close();
    await browser.close();
    
    console.log('Screenshots saved to: ' + screenshotsDir);
    
  } catch (error) {
    console.error('Error: ' + error.message);
    if (browser) await browser.close();
    process.exit(1);
  }
}

runTest();
