import { chromium } from 'playwright';
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1600, height: 900 } });
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto('http://localhost:5199/');
await page.waitForSelector('#btn-new');
await page.evaluate(() => localStorage.clear());
await page.click('#btn-new');
await page.waitForTimeout(600);
await page.screenshot({ path: '/tmp/p1-day.png' });

// camera follow: walk south through the gate region
await page.keyboard.down('ArrowDown');
await page.waitForTimeout(2600);
await page.keyboard.up('ArrowDown');
await page.waitForTimeout(200);
const pos = await page.evaluate(() => window.__game.playerPos);
const sp = await page.evaluate(() => { const p = window.__game.playerPos; return window.__game.screenPos(Math.floor(p.x), Math.floor(p.y)); });
console.log('south pos', JSON.stringify(pos), 'screen', JSON.stringify(sp), 'viewport 1600x900');
await page.screenshot({ path: '/tmp/p2-south.png' });

// click-to-till: click tile north of player feet with hoe
await page.keyboard.press('1');
const feet = await page.evaluate(() => { const p = window.__game.playerPos; return { x: Math.floor(p.x), y: Math.floor(p.y) }; });
const t = { x: feet.x, y: feet.y - 1 };
const before = await page.evaluate(([x, y]) => window.__game.tileAt(x, y), [t.x, t.y]);
const click = await page.evaluate(([x, y]) => window.__game.screenPos(x, y), [t.x, t.y]);
await page.mouse.click(click.x, click.y);
await page.waitForTimeout(400);
const after = await page.evaluate(([x, y]) => window.__game.tileAt(x, y), [t.x, t.y]);
console.log('click-to-till tile', JSON.stringify(t), 'before', before?.kind, 'after', after?.kind);

// tileAt safety
const safe = await page.evaluate(() => {
  try { return [window.__game.tileAt(NaN, NaN), window.__game.tileAt(2, 3.7)?.kind, window.__game.tileAt(-9, 99)] .map(v => JSON.stringify(v ?? null)).join(' | '); }
  catch (e) { return 'THROWS ' + e.message; }
});
console.log('tileAt safety:', safe);

// dusk + night shots
await page.evaluate(() => window.__game.debugSetTime(0.7));
await page.waitForTimeout(400);
await page.screenshot({ path: '/tmp/p3-sunset.png' });
await page.evaluate(() => window.__game.debugSetTime(0.93));
await page.waitForTimeout(400);
await page.screenshot({ path: '/tmp/p4-night.png' });

// mobile portrait
const m = await browser.newPage({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true });
await m.goto('http://localhost:5199/');
await m.waitForSelector('#btn-new');
await m.evaluate(() => localStorage.clear());
await m.tap('#btn-new');
await m.waitForTimeout(600);
await m.screenshot({ path: '/tmp/p5-mobile.png' });

console.log('errors:', errors.length ? errors.join('\n') : 'none');
await browser.close();
