import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4202;
const server = spawn('node', ['node_modules/vite/bin/vite.js', 'preview', '--port', String(PORT), '--strictPort'], { cwd: process.cwd(), stdio: 'pipe' });
const waitServer = () => new Promise((res, rej) => { const t=setTimeout(()=>rej('timeout'),30000); server.stdout.on('data',d=>{if(d.toString().includes('Local:')){clearTimeout(t);res();}}); server.stderr.on('data',d=>{if(d.toString().includes('Local:')){clearTimeout(t);res();}});});
try {
  await waitServer();
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
  page.on('pageerror', (e) => console.log('PAGEERR', e.message));
  await page.goto(`http://localhost:${PORT}/`, { waitUntil: 'load', timeout: 15000 });
  await page.waitForTimeout(800);
  await page.keyboard.press('Enter');
  await page.waitForTimeout(1200);
  // dismiss dialogue
  await page.keyboard.press('e'); await page.waitForTimeout(200); await page.keyboard.press('e'); await page.waitForTimeout(200);

  // Test: is UIScene dialogue blocking? Check UIScene input handlers consume keydown
  // Focus the canvas
  await page.click('canvas');
  await page.waitForTimeout(200);

  // Test arrow keys (cursors) and check global keydown listener
  await page.keyboard.down('ArrowRight');
  await page.waitForTimeout(200);
  const arrowState = await page.evaluate(() => {
    const h = window.game.scene.getScene('HouseScene');
    return { cursorRight: h.cursors.right.isDown, wasdD: h.wasd.D.isDown, inputEnabled: h.input.enabled };
  });
  console.log('ArrowRight held:', JSON.stringify(arrowState));
  await page.keyboard.up('ArrowRight');

  // Check if maybe the scene's update isn't running (frozen?)
  const updateCheck = await page.evaluate(() => {
    const h = window.game.scene.getScene('HouseScene');
    return { sceneActive: h.scene.isActive(), frozen: h.player.frozen, lastUpdate: h.sys.settings.active };
  });
  console.log('scene status:', JSON.stringify(updateCheck));

  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
