import sys
from playwright.sync_api import sync_playwright

BASE = "http://localhost:8899"
PAGES = ["/index.html", "/services.html", "/how-it-works.html", "/pricing.html", "/about.html", "/faq.html", "/contact.html", "/portal/index.html"]

errors_found = False
with sync_playwright() as p:
    browser = p.chromium.launch(executable_path="/opt/pw-browsers/chromium")
    page = browser.new_page(viewport={"width": 1280, "height": 900})
    console_errors = []
    page.on("console", lambda msg: console_errors.append(msg.text) if msg.type == "error" else None)
    page.on("pageerror", lambda exc: console_errors.append("PAGEERROR: " + str(exc)))

    for path in PAGES:
        console_errors.clear()
        resp = page.goto(BASE + path, wait_until="networkidle", timeout=15000)
        status = resp.status if resp else "NO RESPONSE"
        title = page.title()
        h1_count = page.locator("h1").count()
        print(f"{path:30s} status={status} title={title!r} h1_count={h1_count} console_errors={len(console_errors)}")
        for e in console_errors:
            print("   ERR:", e[:200])
            errors_found = True

    # WhatsApp widget check on home
    page.goto(BASE + "/index.html", wait_until="networkidle")
    wa_fab = page.locator(".wa-fab")
    print("WhatsApp FAB present:", wa_fab.count() == 1)
    wa_fab.click()
    panel_open = page.locator(".wa-panel.open").count() == 1
    print("WhatsApp panel opens on click:", panel_open)
    wa_link = page.locator(".wa-action.wa").get_attribute("href")
    print("WhatsApp link:", wa_link)
    page.screenshot(path="/home/claude/site/_screenshot_home.png", full_page=False)

    # Mobile nav check
    page.set_viewport_size({"width": 390, "height": 844})
    page.goto(BASE + "/index.html", wait_until="networkidle")
    toggle_visible = page.locator(".nav-toggle").is_visible()
    print("Mobile nav toggle visible at 390px:", toggle_visible)
    page.screenshot(path="/home/claude/site/_screenshot_mobile.png")

    # Portal auth screen
    page.set_viewport_size({"width": 1280, "height": 900})
    page.goto(BASE + "/portal/index.html", wait_until="networkidle")
    page.screenshot(path="/home/claude/site/_screenshot_portal.png")
    reg_tab = page.locator('.auth-tab[data-tab="register"]')
    reg_tab.click()
    page.wait_for_timeout(300)
    tier_visible = page.locator(".tier-picker").is_visible()
    print("Register tier picker visible:", tier_visible)
    page.screenshot(path="/home/claude/site/_screenshot_portal_register.png")

    browser.close()

sys.exit(1 if errors_found else 0)
