// smoke5.mjs: verify all 4 endings trigger + scene transitions.
import { chromium } from 'playwright';
import { spawn } from 'child_process';

const PORT = 4182;
const server = spawn('node', ['node_modules/vite/bin/vite.js', 'preview', '--port', String(PORT), '--strictPort'], {
  cwd: process.cwd(), stdio: 'pipe',
});
const waitServer = () => new Promise((resolve, reject) => {
  const t = setTimeout(() => reject(new Error('server timeout')), 30000);
  server.stdout.on('data', (d) => { if (d.toString().includes('Local:')) { clearTimeout(t); resolve(); } });
  server.stderr.on('data', (d) => { if (d.toString().includes('Local:')) { clearTimeout(t); resolve(); } });
});

const errors = [];
const checks = {};
function check(name, cond) { checks[name] = !!cond; if (!cond) errors.push('CHECK FAIL: ' + name); }

async function activeScenes(page) {
  return page.evaluate(() => window.game.scene.scenes.filter(s => s.scene.isActive()).map(s => s.scene.key));
}

try {
  await waitServer();
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
  page.on('pageerror', (err) => { errors.push('PAGEERROR: ' + err.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 the opening morning dialogue (E advances/closes) — wait for it then close
  await page.waitForTimeout(300);
  for (let i=0;i<6;i++){ await page.keyboard.press('e'); await page.waitForTimeout(200); }
  await page.waitForTimeout(400);

  // Walk down to door — auto-door triggers on contact
  await page.keyboard.down('s');
  for (let i = 0; i < 30; i++) {
    await page.waitForTimeout(200);
    const sc = await activeScenes(page);
    if (sc.includes('PlazaScene')) break;
  }
  await page.keyboard.up('s');
  await page.waitForTimeout(900);
  let sc = await activeScenes(page);
  check('transition_to_plaza', sc.includes('PlazaScene'));
  check('house_stopped', !sc.includes('HouseScene'));

  // Test each ending via director + scene start (simulate debug forceEnding)
  for (const e of ['E1','E2','E3','E4']) {
    await page.evaluate((ending) => {
      const d = window.director;
      // stop all map scenes
      const g = window.game;
      for (const k of ['HouseScene','PlazaScene','BakeryScene','ShopScene','ClinicScene','LakeScene','FieldScene','WellAreaScene','FogBoundaryScene','WhiteLayerScene']) g.scene.stop(k);
      g.scene.stop('UIScene');
      g.scene.start('EndingScene', { ending });
    }, e);
    await page.waitForTimeout(1500);
    sc = await activeScenes(page);
    check('ending_' + e + '_scene_active', sc.includes('EndingScene'));
    await page.screenshot({ path: 'shots/ending_' + e + '.png' });
    // go back to title for next iteration
    await page.evaluate(() => { window.game.scene.start('TitleScene'); });
    await page.waitForTimeout(600);
    await page.keyboard.press('Enter');
    await page.waitForTimeout(800);
  }

  await browser.close();
} catch (e) {
  errors.push('TEST_FAIL: ' + e.message);
} finally {
  server.kill('SIGTERM');
}
console.log('=== CHECKS ===', JSON.stringify(checks, null, 2));
console.log('=== ERRORS (' + errors.length + ') ===');
errors.slice(0, 20).forEach((e) => console.log(e));
process.exit(errors.length > 0 ? 1 : 0);
