// smoke3.mjs: deterministic state checks via exposeFunction / evaluate.
import { chromium } from 'playwright';
import { spawn } from 'child_process';

const PORT = 4180;
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 results = {};
try {
  await waitServer();
  const browser = await chromium.launch();
  const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
  page.on('console', (msg) => { if (msg.type() === 'error') errors.push(msg.text()); });
  page.on('pageerror', (err) => { errors.push('PAGEERROR: ' + err.message); });

  await page.goto(`http://localhost:${PORT}/`, { waitUntil: 'load', timeout: 15000 });
  await page.waitForTimeout(800);

  // check title screen text
  results.titleCanvas = await page.evaluate(() => !!document.querySelector('canvas'));
  // count active Phaser scenes by reading the game registry
  await page.keyboard.press('Enter');
  await page.waitForTimeout(1200);

  // probe: read active scenes + WebGL pixels
  const probeHUD = await page.evaluate(() => {
    const g = (window).game;
    const scenes = g ? g.scene.scenes.map(s => ({ key: s.scene.key, active: s.scene.isActive(), visible: s.scene.isVisible() })) : [];
    // WebGL pixel probe for HUD region
    const c = document.querySelector('canvas');
    const gl = c.getContext('webgl2') || c.getContext('webgl');
    let hudYellow = 0, sceneNonblack = 0;
    if (gl) {
      const w = c.width, h = c.height;
      const fb = new Uint8Array(w * h * 4);
      gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, fb);
      // HUD petals at display (14,18): WebGL y = h-18=162, x=14. Sample a 24x24 box there.
      for (let dy = 0; dy < 24; dy++) {
        for (let dx = 0; dx < 24; dx++) {
          const x = 4 + dx, y = (h - 30) + dy; // around top-left HUD
          const i = (y * w + x) * 4;
          const r = fb[i], gg = fb[i+1], b = fb[i+2];
          if (r > 150 && gg > 120 && b < 120) hudYellow++;
        }
      }
      // also count any non-black in the HUD box (petals brown/yellow, center orange)
      let hudAny = 0;
      for (let dy = 0; dy < 30; dy++) {
        for (let dx = 0; dx < 30; dx++) {
          const x = 0 + dx, y = (h - 30) + dy;
          const i = (y * w + x) * 4;
          if (fb[i] > 30 || fb[i+1] > 30 || fb[i+2] > 30) hudAny++;
        }
      }
      window.__hudAny = hudAny;
      for (let y = 0; y < h; y++) {
        for (let x = 0; x < w; x++) {
          const i = (y * w + x) * 4;
          if (fb[i] > 20 || fb[i+1] > 20 || fb[i+2] > 20) sceneNonblack++;
        }
      }
    }
    return { scenes, hudYellow, hudAny: window.__hudAny, sceneNonblack, canvasSize: c ? [c.width, c.height] : null, numCanvases: document.querySelectorAll('canvas').length };
    return { scenes, hudYellow, sceneNonblack, canvasSize: c ? [c.width, c.height] : null, numCanvases: document.querySelectorAll('canvas').length };
  });
  results.probe = probeHUD;

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