import puppeteer from 'puppeteer-core';
const browser = await puppeteer.launch({
    executablePath: '/usr/bin/chromium', headless: true,
    args: ['--no-sandbox', '--enable-unsafe-swiftshader', '--use-angle=swiftshader',
           '--autoplay-policy=no-user-gesture-required', '--window-size=960,540']
});
const page = await browser.newPage();
await page.setViewport({ width: 960, height: 540 });
page.on('pageerror', (e) => console.log(`[ошибка] ${e.message}`));
const booted = new Promise((r) => page.on('console', (m) => { if (m.text().includes('[location]')) r(); }));
await page.goto('http://localhost:5201/', { waitUntil: 'networkidle2', timeout: 20000 });
await new Promise((r) => setTimeout(r, 2000));
await page.mouse.click(480, 283);
await booted;
await new Promise((r) => setTimeout(r, 1500));

// Клик по тайлу Милы (16,12) издалека.
const pt = await page.evaluate(() => {
    const g = window.__game;
    const sc = g.scenes.current;
    const p = sc.tileCenter(16, 12);
    const rect = document.querySelector('canvas').getBoundingClientRect();
    const wr = g.renderer.worldRoot.position;
    return { x: rect.left + ((p.x + wr.x) / 480) * rect.width,
             y: rect.top + ((p.y + wr.y) / 270) * rect.height };
});
await page.mouse.click(pt.x, pt.y);
await new Promise((r) => setTimeout(r, 400));

const moving = await page.evaluate(() => window.__game.scenes.current.player.moving);
console.log(`Герой пошёл: ${moving}`);

// Ждём, пока диалог начнётся (подошёл и заговорил)
for (let i = 0; i < 20; i++) {
    const st = await page.evaluate(() => ({
        active: window.__game.scenes.current.dialogue.active,
        tile: window.__game.scenes.current.player.currentTile()
    }));
    if (st.active) {
        console.log(`Диалог начался, герой на тайле (${st.tile.x},${st.tile.y}) — рядом с Милой (16,12)`);
        break;
    }
    await new Promise((r) => setTimeout(r, 200));
}
await page.screenshot({ path: '/tmp/far_check.png' });
await browser.close();
