import { chromium } from 'playwright';
import { spawn } from 'child_process';
const PORT = 4214;
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(300);
  // house -> plaza
  await page.keyboard.down('s'); await page.waitForTimeout(1500); 
  // wait for plaza
  for (let i=0;i<10;i++){ await page.waitForTimeout(300); 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(600);

  // Now in plaza. Check player position and doors
  const state = await page.evaluate(() => {
    const p = window.game.scene.getScene('PlazaScene');
    return {
      px: p.player.x, py: p.player.y,
      doors: p.doors.map(d=>({x:d.x,y:d.y,target:d.target})),
    };
  });
  console.log('plaza state:', JSON.stringify(state));

  // Directly teleport player to bakery door and check if auto-transition works
  await page.evaluate(() => { window.game.scene.getScene('PlazaScene').player.setPosition(80, 144); });
  await page.waitForTimeout(800);
  let a = await page.evaluate(() => window.game.scene.scenes.filter(s=>s.scene.isActive()).map(s=>s.scene.key));
  console.log('after teleport to bakery door:', JSON.stringify(a));

  // If still in plaza, press E
  if (a.includes('PlazaScene')) {
    await page.keyboard.press('e');
    await page.waitForTimeout(800);
    a = await page.evaluate(() => window.game.scene.scenes.filter(s=>s.scene.isActive()).map(s=>s.scene.key));
    console.log('after E at bakery door:', JSON.stringify(a));
  }
  await browser.close();
} catch(e){ console.log('FAIL', e.message); } finally { server.kill('SIGTERM'); }
