import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4217;
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));
  page.on('console', (msg) => { if (msg.type()==='error') console.log('CONSOLE_ERR', msg.text()); });
  await page.goto(`http://localhost:${PORT}/`, { waitUntil: 'load', timeout: 15000 });
  await page.waitForTimeout(800);
  await page.keyboard.press('Enter'); await page.waitForTimeout(1200);
  for (let i=0;i<4;i++){ await page.keyboard.press('e'); await page.waitForTimeout(150); }
  await page.click('canvas'); await page.waitForTimeout(300);
  // house -> plaza
  await page.keyboard.down('s');
  for (let i=0;i<15;i++){ await page.waitForTimeout(250); const a=await page.evaluate(()=>window.game.scene.scenes.filter(s=>s.scene.isActive()).map(s=>s.scene.key)); if(a.includes('PlazaScene')) break; }
  await page.keyboard.up('s'); await page.waitForTimeout(800);

  // Check plaza player keys and update status
  const info = await page.evaluate(() => {
    const p = window.game.scene.getScene('PlazaScene');
    const pl = p.player;
    return {
      px: pl.x, py: pl.y,
      moving: pl.moving,
      frozen: pl.frozen,
      hasKUp: !!pl.kUp,
      kUpIsDown: pl.kUp && pl.kUp.isDown,
      wasdLen: pl.wasdKeys ? pl.wasdKeys.length : 0,
      wasdWDown: pl.wasdKeys && pl.wasdKeys[0] ? pl.wasdKeys[0].isDown : null,
      sceneUpdateActive: p.scene.isActive(),
      doorCooldown: p.doorCooldown,
      timeNow: p.time.now,
    };
  });
  console.log('plaza player info:', JSON.stringify(info));

  // hold w and check if key isDown updates
  await page.keyboard.down('w');
  await page.waitForTimeout(400);
  const wInfo = await page.evaluate(() => {
    const pl = window.game.scene.getScene('PlazaScene').player;
    return { kUpDown: pl.kUp.isDown, wasdWDown: pl.wasdKeys[0].isDown, px: pl.x, py: pl.y, vy: pl.body.velocity.y, moving: pl.moving };
  });
  console.log('w held:', JSON.stringify(wInfo));
  await page.keyboard.up('w');

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