"""t1196 (last planet), t1197 (+x% combo), t1198 (defeated count) checks.
Usage: python3 test/t1196-t1198-playwright.py ROOT_URL [local]"""
import sys
from playwright.sync_api import sync_playwright

URL = sys.argv[1].rstrip("/") + "/"
LOCAL = len(sys.argv) > 2 and sys.argv[2] == "local"
SHOTS = "/workspace/meteors-shots/t1196-"
fails = []
def check(ok, msg):
    print(("OK   " if ok else "FAIL ") + msg)
    if not ok: fails.append(msg)

def pick(page, pid):
    page.click("#btn-play"); page.wait_for_selector("#planet-select:not([hidden])")
    page.click(f'#planet-grid [data-planet="{pid}"]')

def selected(page):
    return page.evaluate("() => app.selectedPlanetId")

with sync_playwright() as p:
    br = p.chromium.launch()
    # ---- logged out: localStorage
    ctx = br.new_context(viewport={"width": 1280, "height": 800}); page = ctx.new_page()
    errs = []; page.on("pageerror", lambda e: errs.append(str(e)))
    page.goto(URL + "index.html", wait_until="networkidle")
    ids = page.evaluate("() => Planet.allPlanets().map(p => p.id)")
    other = [i for i in ids if i != "terra"][0]
    pick(page, other); page.click("#btn-planet-go"); page.wait_for_timeout(300)
    page.goto(URL + "index.html", wait_until="networkidle")
    check(selected(page) == other, f"logged out: {other} remembered via localStorage after reload ({selected(page)})")
    for btn, ctxname in (("#btn-play", "Spelen"), ("#btn-offline", "Offline Strijd")):
        page.click(btn); page.wait_for_selector("#planet-select:not([hidden])")
        sel = page.evaluate("() => (document.querySelector('#planet-grid .selected, #planet-grid [aria-pressed=\"true\"], #planet-grid [aria-selected=\"true\"]')||{}).dataset")
        check(bool(sel) and sel.get("planet") == other, f"logged out: {ctxname} planet select pre-selects {other} ({sel})")
        page.screenshot(path=SHOTS + f"preselect-{ctxname.split()[0].lower()}.png")
        page.click("#btn-planet-back")

    # ---- t1197 indicator + combo (offline, real core)
    page.click("#btn-play"); page.wait_for_selector("#planet-select:not([hidden])"); page.click("#btn-planet-go")
    page.wait_for_function("() => app.mode === 'playing' && app.core")
    res = page.evaluate("""() => {
        const g = app.core; g.noSpawn = true;
        for (const b of Object.values(g.blocks || {})) {}
        const out = [];
        for (let k = 0; k < 3; k++) {
            for (let c = 0; c < 10; c++) for (let y = 0; y < 13; y++) { const b = g.at ? g.at(c, y) : null; if (b) g.removeBlock && g.removeBlock(b); }
            g.place(0, 0, 1 + k); g.place(1, 0, 1 + k); g.place(2, 0, 1 + k);
            const l = g.resolveMatches();
            out.push(l.length ? Math.round((l[0].chainBonus - 1) * 100) : null);
        }
        return { out, combo: g.combo, ind: g.lastChainIndicator };
    }""")
    page.wait_for_timeout(150)
    txt = page.evaluate("() => { const e = document.getElementById('chain-indicator'); return e && !e.hidden ? e.textContent : null; }")
    style = page.evaluate("() => { const s = getComputedStyle(document.getElementById('chain-indicator')); return [s.color, s.webkitTextStrokeColor, s.webkitTextStrokeWidth]; }")
    check(res["out"] == [0, 5, 10], f"combo bonus per match {res['out']} (combo {res['combo']})")
    check(txt == "+10%", f"indicator text {txt!r}")
    check("255, 230, 0" in style[0] and "255, 122, 0" in style[1], f"yellow fill, orange stroke {style}")
    page.screenshot(path=SHOTS.replace("t1196", "t1197") + "plus-pct.png")
    el = page.locator("#chain-indicator")
    if el.is_visible(): el.screenshot(path=SHOTS.replace("t1196", "t1197") + "plus-pct-crop.png")
    page.evaluate("() => { for (let i = 0; i < 120; i++) app.core.tick(0.05); }")
    check(page.evaluate("() => app.core.combo") == 0, "combo reset after 6 s without a match")
    page.evaluate("() => teardownPlay && teardownPlay()") if False else None
    ctx.close()

    # ---- t1198 offline result text
    ctx = br.new_context(viewport={"width": 1280, "height": 800}); page = ctx.new_page()
    page.goto(URL + "index.html", wait_until="networkidle")
    page.click("#btn-offline"); page.wait_for_selector("#planet-select:not([hidden])"); page.click("#btn-planet-go")
    page.wait_for_function("() => app.battle && app.mode === 'playing'")
    page.evaluate("() => { for (const b of app.battle.bots) b.core.state = 'gameover'; }")
    page.wait_for_function("() => app.battle && app.battle.round === 2 && app.mode === 'playing'", timeout=15000)
    page.evaluate("() => { app.battle.bots[0].core.state = 'gameover'; }")
    page.wait_for_timeout(300)
    page.evaluate("() => { app.core.state = 'gameover'; }")
    page.wait_for_selector("#offline-result:not([hidden])", timeout=15000)
    reached = page.inner_text("#offline-reached-line"); detail = page.inner_text("#offline-result-detail")
    check(detail.strip() == "2 opponents defeated", f"en result: {reached!r} / {detail!r}")
    page.screenshot(path=SHOTS.replace("t1196", "t1198") + "result-en.png")
    page.evaluate("() => I18n.setLocale('nl'); ") if True else None
    page.evaluate("() => { if (typeof showOfflineResult === 'function') { app.offlineResultShown = false; showOfflineResult(); } }")
    page.wait_for_timeout(200)
    detail_nl = page.inner_text("#offline-result-detail"); reached_nl = page.inner_text("#offline-reached-line")
    check(detail_nl.strip() == "2 tegenstanders verslagen" and "bereikt" in reached_nl, f"nl result: {reached_nl!r} / {detail_nl!r}")
    page.screenshot(path=SHOTS.replace("t1196", "t1198") + "result-nl.png")
    ctx.close()

    # ---- logged in: server profile (local test login only)
    if LOCAL:
        ctx = br.new_context(viewport={"width": 1280, "height": 800}); page = ctx.new_page()
        page.goto(URL + "auth.php?test=2&next=index.html", wait_until="domcontentloaded")
        page.goto(URL + "index.html", wait_until="networkidle")
        page.wait_for_function("() => Online.me")
        pid = page.evaluate("""async () => {
            const cols = ['terra-ember','terra-aqua','terra-leaf','terra-sun','terra-orchid'];
            const r = await Online.request('planet_save', { planet: { name: 'Proef', people: 'Proevers', jumpsToClear: 2.5, fallTime: 2, riseTime: 1, colors: cols } });
            await Online.refresh(); return r.planet.id; }""")
        pick(page, pid); page.click("#btn-planet-go"); page.wait_for_timeout(600)
        ctx2 = br.new_context(viewport={"width": 1280, "height": 800}); p2 = ctx2.new_page()
        p2.goto(URL + "auth.php?test=2&next=index.html", wait_until="domcontentloaded")
        p2.goto(URL + "index.html", wait_until="networkidle"); p2.wait_for_function("() => Online.me")
        p2.wait_for_timeout(400)
        check(p2.evaluate("() => Online.lastPlanet") == pid and selected(p2) == pid, f"logged in: custom planet {pid} restored from the profile in a fresh browser ({selected(p2)})")
        p2.click("#btn-online"); p2.wait_for_timeout(500)
        p2.screenshot(path=SHOTS + "loggedin-online.png")
        page.evaluate(f"async () => {{ await Online.request('planet_delete', {{ id: '{pid}' }}); }}")
        ctx3 = br.new_context(viewport={"width": 1280, "height": 800}); p3 = ctx3.new_page()
        p3.goto(URL + "auth.php?test=2&next=index.html", wait_until="domcontentloaded")
        p3.goto(URL + "index.html", wait_until="networkidle"); p3.wait_for_function("() => Online.me"); p3.wait_for_timeout(400)
        check(p3.evaluate("() => Online.lastPlanet") is None and selected(p3) == "terra", f"deleted custom planet → falls back to Terra ({selected(p3)})")
        ctx.close(); ctx2.close(); ctx3.close()
    check(not errs, f"no page errors {errs}")
    br.close()
print("ALL OK" if not fails else f"{len(fails)} FAILED")
sys.exit(1 if fails else 0)
