"""Auth page checks (19 Nov 2026): 3 viewports x 4 themes x 2 tabs, states idle / google / passkey / mail / back.
Pass = 0 console or JS errors, 0 horizontal overflow, labels fit their buttons, hidden layers inert, focus lands
where it should, page height unchanged by any state, and the split ends at 64/36.
Run: python3 -m http.server 8951 (in this component folder), then python3 tests/verify_auth.py"""
import json, os, sys
from playwright.sync_api import sync_playwright
EXE = "/home/box/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome"
BASE = os.environ.get("BASE", "http://localhost:8951/") + "auth/"
VPS = [(390, 844), (820, 1180), (1440, 900)]
THEMES = ["pearl", "champagne", "midnight", "amethyst"]
PROBE = """() => {
  const d = document.documentElement, out = [];
  if (d.scrollWidth > d.clientWidth) out.push('page overflow ' + d.scrollWidth);
  document.querySelectorAll('body *').forEach(el => {
    const r = el.getBoundingClientRect(); if (!r.width) return;
    if (el.closest('.sheet') || el.closest('[inert]')) return;
    if (r.right > innerWidth + .5 || r.left < -.5) out.push('offscreen ' + el.className);
  });
  document.querySelectorAll('.pick').forEach(b => {
    const lab = [...b.querySelectorAll('.lb>span')].find(s => getComputedStyle(s).position === 'static');
    const svg = b.querySelector('svg').getBoundingClientRect(), br = b.getBoundingClientRect(), lr = lab.getBoundingClientRect();
    if (svg.left < br.left + 6 || lr.right > br.right - 6) out.push('label clipped ' + b.dataset.act + ' ' + Math.round(br.width));
  });
  document.querySelectorAll('[data-layer]').forEach(el => {
    const shown = getComputedStyle(el).visibility === 'visible';
    if (shown === el.hasAttribute('inert')) out.push('layer mismatch ' + el.dataset.layer);
  });
  const [a, b] = [...document.querySelectorAll('.pick')].map(x => x.getBoundingClientRect().width);
  return { out, h: document.body.scrollHeight, stage: document.getElementById('stage').getBoundingClientRect().height,
           split: Math.round(100 * a / (a + b)), focus: document.activeElement.id || document.activeElement.dataset.act || document.activeElement.tagName };
}"""
fails, runs = [], 0
with sync_playwright() as p:
    br = p.chromium.launch(executable_path=EXE)
    for w, h in VPS:
        for t in THEMES:
            for tab in ["signin", "create"]:
                ctx = br.new_context(viewport={"width": w, "height": h})
                pg = ctx.new_page(); errs = []
                pg.on("console", lambda m: m.type == "error" and errs.append(m.text)); pg.on("pageerror", lambda e: errs.append(str(e)))
                pg.goto(f"{BASE}?t={t}&tab={tab}"); pg.wait_for_timeout(600)
                def step(name, action, expect_split=None, expect_focus=None):
                    global runs
                    runs += 1
                    if action: action(); pg.wait_for_timeout(750)
                    r = pg.evaluate(PROBE); bad = list(r["out"])
                    if expect_split is not None and abs(r["split"] - expect_split) > 1: bad.append(f"split {r['split']}")
                    if expect_focus and r["focus"] != expect_focus: bad.append(f"focus {r['focus']}")
                    if r["stage"] != base["stage"]: bad.append(f"stage height {r['stage']} vs {base['stage']}")
                    if errs: bad.append("errors " + "; ".join(errs))
                    if bad: fails.append(f"{w} {t} {tab} {name}: {bad}")
                base = pg.evaluate(PROBE)
                step("idle", None, 50)
                step("google", lambda: pg.click("[data-act=google]"), 64, "google")
                step("passkey", lambda: pg.click("[data-act=passkey]"), 36, "passkey")
                step("back", lambda: pg.click("[data-act=back]"), 50)
                step("mail", lambda: pg.click("[data-act=email]"), None, "email")
                step("back-esc", lambda: pg.keyboard.press("Escape"), 50, "email")
                step("start", lambda: (pg.click("[data-act=google]"), pg.wait_for_timeout(700), pg.click("[data-act=google]")), 64)
                ctx.close()
    # reduced motion: states apply instantly, nothing left mid-way
    ctx = br.new_context(viewport={"width": 390, "height": 844}, reduced_motion="reduce"); pg = ctx.new_page()
    pg.goto(BASE); pg.wait_for_timeout(300); pg.click("[data-act=google]"); pg.wait_for_timeout(60)
    sp = pg.evaluate(PROBE)["split"]; runs += 1
    if abs(sp - 64) > 1: fails.append(f"reduced motion split {sp}")
    # motion budget: longest frame and page height during the split + the email open
    pg = br.new_page(viewport={"width": 390, "height": 844}); pg.goto(BASE); pg.wait_for_timeout(500)
    pg.evaluate("""() => { window.__f = []; window.__h = new Set(); let l = performance.now();
      (function tick(n){ window.__f.push(n - l); l = n; window.__h.add(document.documentElement.scrollHeight); requestAnimationFrame(tick); })(performance.now()); }""")
    pg.click("[data-act=google]"); pg.wait_for_timeout(700); pg.click("[data-act=passkey]"); pg.wait_for_timeout(700)
    pg.click("[data-act=back]"); pg.wait_for_timeout(500); pg.click("[data-act=email]"); pg.wait_for_timeout(600)
    m = pg.evaluate("() => ({ longest: Math.max(...window.__f.slice(2)), heights: [...window.__h] })"); runs += 1
    if m["longest"] > 25 or len(m["heights"]) != 1: fails.append(f"motion {m}")
    print(json.dumps({"motion": m}))
    br.close()
print(f"{runs} runs, {len(fails)} failed")
for f in fails: print(" -", f)
sys.exit(1 if fails else 0)
