import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4210;
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);
  for (let i=0;i<4;i++){ await page.keyboard.press('e'); await page.waitForTimeout(150); }
  await page.click('canvas'); await page.waitForTimeout(200);

  // Try to walk to door: door at tile (5,7)=(80,112). Player at ~(96,64).
  // Move left first to align x, then down.
  await page.keyboard.down('a'); await page.waitForTimeout(500); await page.keyboard.up('a');
  await page.waitForTimeout(100);
  const afterLeft = await page.evaluate(() => { const p=window.game.scene.getScene('HouseScene').player; return {x:p.x,y:p.y}; });
  console.log('after left:', JSON.stringify(afterLeft));

  // Now move down toward door
  await page.keyboard.down('s'); 
  for (let i=0;i<8;i++){ await page.waitForTimeout(300); const p=await page.evaluate(()=>{const pl=window.game.scene.getScene('HouseScene').player;return{x:pl.x,y:pl.y,vx:pl.body.velocity.x,vy:pl.body.velocity.y};}); console.log('down step',i,JSON.stringify(p)); if(p.y>100) break; }
  await page.keyboard.up('s');
  await page.waitForTimeout(200);

  const nearDoor = await page.evaluate(() => {
    const h = window.game.scene.getScene('HouseScene');
    const p = h.player;
    const door = h.doors[0];
    const dist = Math.hypot(p.x-door.x, p.y-door.y);
    return { px:p.x, py:p.y, doorX:door.x, doorY:door.y, dist, worldBounds: {w:h.physics.world.bounds.width, h:h.physics.world.bounds.height} };
  });
  console.log('near door:', JSON.stringify(nearDoor));

  // press E to transition
  await page.keyboard.press('e');
  await page.waitForTimeout(1500);
  const activeScenes = await page.evaluate(() => window.game.scene.scenes.filter(s=>s.scene.isActive()).map(s=>s.scene.key));
  console.log('active scenes after E:', JSON.stringify(activeScenes));

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