#!/usr/bin/env python3
"""t1179/t1180 real-browser checks.

- Players without a profile picture (null avatar) and with a picture URL that
  404s are visible on the board as a coloured circle with initials, stay
  visible across several 3 s polls and after taps; also in the lobby list
  and the menu.
- The game view fits the viewport on mobile (412x915, 390x844, 460x1000)
  and desktop: no page scroll, the header does not overlap the HUD, the
  timeline is fully on screen and not covered by the language button.
Usage: python3 test/avatar-layout-playwright.py [BASE]
"""
import sys
from pathlib import Path
from urllib.parse import quote

from playwright.sync_api import sync_playwright

BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://127.0.0.1:8080'
OUT = Path('/workspace/allianties-shots')
OUT.mkdir(parents=True, exist_ok=True)
FAILS = []


def check(cond, msg):
    print(('  ok  ' if cond else '  FAIL  ') + msg)
    if not cond:
        FAILS.append(msg)


def shot(page, name):
    page.screenshot(path=str(OUT / ('t1179-' + name + '.png')), full_page=False)
    print('    shot', OUT / ('t1179-' + name + '.png'))


TOKENS_JS = """() => Array.from(document.querySelectorAll('#board .cell .piece')).map(el => {
  const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);
  const ini = el.querySelector('.piece-initials');
  const img = el.querySelector('img');
  return { w: r.width, h: r.height, vis: cs.visibility, op: parseFloat(cs.opacity), disp: cs.display,
           bg: cs.backgroundColor, ini: ini ? ini.textContent : null,
           iniVis: ini ? getComputedStyle(ini).visibility : null,
           img: !!img, hasImg: el.classList.contains('has-img'), label: el.getAttribute('aria-label') };
})"""

LAYOUT_JS = """() => {
  const se = document.scrollingElement;
  const before = se.scrollTop; window.scrollTo(0, 400); const after = se.scrollTop; window.scrollTo(0, 0);
  const rb = id => { const e = document.getElementById(id); if (!e || e.hidden) return null; const r = e.getBoundingClientRect(); return {t: r.top, b: r.bottom, l: r.left, r: r.right}; };
  return { vh: innerHeight, vw: innerWidth, sh: se.scrollHeight, sw: se.scrollWidth, scrolled: after - before,
           top: rb('top-bar'), hud: rb('game-hud'), board: rb('board'), tl: rb('timeline'),
           live: rb('tl-live'), lang: rb('lang-current') };
}"""


def visible_tokens(page, label):
    toks = page.evaluate(TOKENS_JS)
    ok = [t for t in toks if t['w'] > 16 and t['h'] > 16 and t['vis'] == 'visible' and t['op'] > 0.5 and t['disp'] != 'none'
          and (t['hasImg'] or (t['ini'] and t['iniVis'] == 'visible'))]
    check(len(toks) == 3 and len(ok) == 3, '%s: 3 visible tokens (%d/%d) %s' % (label, len(ok), len(toks),
          [(t['label'], t['ini'], t['hasImg'], round(t['w'])) for t in toks]))
    return toks


def check_layout(page, label):
    L = page.evaluate(LAYOUT_JS)
    check(L['sh'] <= L['vh'] + 1 and L['scrolled'] == 0, '%s: no vertical page scroll (scrollHeight %d, viewport %d)' % (label, L['sh'], L['vh']))
    check(L['sw'] <= L['vw'] + 1, '%s: no horizontal overflow (%d > %d)' % (label, L['sw'], L['vw']))
    check(L['top']['b'] <= L['hud']['t'] + 0.5, '%s: header (bottom %.0f) above HUD (top %.0f)' % (label, L['top']['b'], L['hud']['t']))
    check(L['tl']['b'] <= L['vh'] + 0.5, '%s: timeline on screen (bottom %.0f / %d)' % (label, L['tl']['b'], L['vh']))
    lv, lg = L['live'], L['lang']
    overlap = lg and not (lv['r'] <= lg['l'] or lv['l'] >= lg['r'] or lv['b'] <= lg['t'] or lv['t'] >= lg['b'])
    check(not overlap, '%s: Live button not covered by the language button' % label)
    tb = L['top']
    hits = page.evaluate("""() => { const r = document.getElementById('lang-current').getBoundingClientRect();
        const ids = ['top-title', 'ap-hms', 'day-label', 'game-hud'];
        return ids.filter(id => { const e = document.getElementById(id); if (!e) return false; let q = e.getBoundingClientRect();
          if (id === 'game-hud') { return !(q.top >= r.bottom); }
          const rg = document.createRange(); rg.selectNodeContents(e); q = rg.getBoundingClientRect(); return [e].some(k => !(q.right <= r.left || q.left >= r.right || q.bottom <= r.top || q.top >= r.bottom)); }); }""")
    check(not hits, '%s: language button overlaps nothing (%s)' % (label, hits))
    tr = page.evaluate("() => document.getElementById('tl-track').getBoundingClientRect().width")
    check(tr >= 100, '%s: timeline track usable width (%.0f px)' % (label, tr))
    check(L['board']['b'] - L['board']['t'] > 150, '%s: board has a usable size (%.0f px)' % (label, L['board']['b'] - L['board']['t']))
    return L


VIEWPORTS = [
    ('mobile-412x915', dict(viewport={'width': 412, 'height': 915}, device_scale_factor=2.6, is_mobile=True, has_touch=True)),
    ('mobile-390x844', dict(viewport={'width': 390, 'height': 844}, device_scale_factor=3, is_mobile=True, has_touch=True)),
    ('mobile-460x1000', dict(viewport={'width': 460, 'height': 1000}, device_scale_factor=2.35, is_mobile=True, has_touch=True)),
    ('desktop-1280x800', dict(viewport={'width': 1280, 'height': 800})),
]


def main():
    with sync_playwright() as p:
        browser = p.chromium.launch()
        host_ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **VIEWPORTS[0][1])
        host = host_ctx.new_page()
        host.goto(BASE + '/auth.php?test=1', wait_until='networkidle')
        host.wait_for_selector('#btn-create')
        host.locator('#btn-create').click()
        host.wait_for_selector('#lobby:not([hidden])')
        code = host.locator('#lobby-code').inner_text().strip()
        guests = []
        for n, mode in ((5, "none"), (6, "broken")):
            ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **VIEWPORTS[1][1])
            g = ctx.new_page()
            g.goto(BASE + '/auth.php?test=%d&avatar=%s&next=%s' % (n, mode, quote('index.html?join=' + code, safe='')), wait_until='networkidle')
            g.wait_for_selector('#lobby:not([hidden])')
            guests.append(g)
        host.wait_for_function("() => App.game && App.game.players.length === 3", timeout=10000)
        host.wait_for_timeout(500)
        lobby_toks = host.evaluate("""() => Array.from(document.querySelectorAll('#lobby-players .piece')).map(el => {
            const r = el.getBoundingClientRect(); const i = el.querySelector('.piece-initials');
            return { w: r.width, ini: i && i.textContent, iniVis: i && getComputedStyle(i).visibility, hasImg: el.classList.contains('has-img') }; })""")
        check(len(lobby_toks) == 3 and all(abs(t['w'] - 40) < 1 and (t['hasImg'] or t['iniVis'] == 'visible') for t in lobby_toks),
              'lobby list: all 3 players visible %s' % lobby_toks)
        shot(host, 'lobby-list-host')
        g9 = guests[0]
        mv = g9.evaluate("() => { const e = document.querySelector('#menu-avatar .piece'); return e ? e.getBoundingClientRect().width : 0; }")
        check(True, 'guest without avatar in lobby (menu avatar width %s, menu hidden on lobby)' % mv)
        host.locator('#btn-start').click()
        host.wait_for_selector('#game:not([hidden])')
        host.wait_for_timeout(800)
        gid = host.evaluate("() => App.game.id")

        # Host view on each viewport (resize the same page, plus a fresh context per viewport).
        for name, opts in VIEWPORTS:
            ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **opts)
            pg = ctx.new_page()
            pg.goto(BASE + '/auth.php?test=1&next=' + quote('index.html', safe=''), wait_until='networkidle')
            pg.wait_for_selector('#btn-create')
            pg.evaluate("(id) => App.openGame(id, 'running')", gid)
            pg.wait_for_selector('#game:not([hidden])')
            pg.wait_for_timeout(800)
            visible_tokens(pg, name + ' initial')
            check_layout(pg, name)
            shot(pg, name + '-game')
            # Survive polls (3 s each).
            pg.wait_for_timeout(7000)
            visible_tokens(pg, name + ' after 2 polls')
            # Tap / click an opponent, close the sheet, still visible.
            opp = pg.locator('#board .cell:has(.piece:not(.has-img))').first
            opp.click()
            pg.wait_for_timeout(300)
            if pg.locator('#sheet:not([hidden])').count():
                shot(pg, name + '-opponent-menu')
                pg.locator('#sheet-close').click()
            pg.wait_for_timeout(3500)
            visible_tokens(pg, name + ' after tap + poll')
            check_layout(pg, name + ' after interaction')
            ctx.close()

        # Avatar-less players' own views (null avatar, broken avatar URL) on mobile.
        for g, label in ((guests[0], 'no-avatar-player'), (guests[1], 'broken-avatar-player')):
            g.reload(wait_until='networkidle')
            if g.locator('#game:not([hidden])').count() == 0:
                g.wait_for_selector('#game:not([hidden])', timeout=10000)
            g.wait_for_timeout(800)
            visible_tokens(g, label + ' own view')
            check_layout(g, label + ' 390x844')
            shot(g, label + '-390x844')
        # Menu avatar for the no-avatar user.
        g9.locator('#btn-settings').click()
        g9.locator('#btn-to-menu').click()
        g9.wait_for_selector('#menu:not([hidden])')
        mt = g9.evaluate("() => { const e = document.querySelector('#menu-avatar .piece'); if (!e) return null; const r = e.getBoundingClientRect(); return { w: r.width, ini: e.querySelector('.piece-initials').textContent }; }")
        check(mt and abs(mt['w'] - 32) < 1 and mt['ini'], 'menu shows initials avatar for no-avatar user: %s' % mt)
        shot(g9, 'menu-no-avatar')
        browser.close()
    print('FAILED:', len(FAILS))
    for f in FAILS:
        print('  -', f)
    sys.exit(1 if FAILS else 0)


if __name__ == '__main__':
    main()
