"""
Audit responsive Socialex.
Capture chaque page aux 3 breakpoints + collecte des metrics auto:
 - overflow horizontal (scrollWidth > clientWidth)
 - elements qui depassent le viewport
 - tailles de police minimales
 - tailles tactiles des boutons / liens
 - presence du burger mobile et son comportement
"""
from playwright.sync_api import sync_playwright
import json
import os

BASE = "https://socialex.pro"
PAGES = [
    ("accueil", "/"),
    ("societes-list", "/societes"),
    ("societes-creation", "/societes/creation-de-societe"),
    ("societes-transfert", "/societes/transfert-de-siege"),
    ("societes-creation-form", "/societes/creation-de-societe/formulaire"),
    ("marques-list", "/marques"),
    ("marques-depot", "/marques/depot-de-marques"),
    ("contact", "/contact"),
]

VIEWPORTS = [
    ("mobile-375", 375, 812),
    ("tablet-768", 768, 1024),
    ("desktop-1280", 1280, 800),
]

OUT = r"c:\Users\Zeiko\Desktop\Socialex\screenshots"
os.makedirs(OUT, exist_ok=True)

AUDIT_JS = r"""
() => {
    const html = document.documentElement;
    const body = document.body;
    const vw = window.innerWidth;
    const vh = window.innerHeight;

    const overflowHorizontal = html.scrollWidth > html.clientWidth;
    const docScrollWidth = html.scrollWidth;

    // chercher elements qui depassent la largeur
    const overflowing = [];
    const all = document.querySelectorAll('*');
    for (const el of all) {
        const r = el.getBoundingClientRect();
        if (r.width === 0 || r.height === 0) continue;
        if (r.right > vw + 1 && r.left < vw) {
            const tag = el.tagName.toLowerCase();
            const cls = (el.className && typeof el.className === 'string') ? el.className.slice(0, 80) : '';
            const txt = (el.innerText || '').slice(0, 60).replace(/\s+/g, ' ');
            overflowing.push({tag, cls, txt, right: Math.round(r.right), left: Math.round(r.left), w: Math.round(r.width)});
            if (overflowing.length > 15) break;
        }
    }

    // boutons / liens trop petits
    const tiny = [];
    const interactive = document.querySelectorAll('a, button, input[type=submit], input[type=button], [role=button]');
    for (const el of interactive) {
        const r = el.getBoundingClientRect();
        if (r.width === 0 || r.height === 0) continue;
        if (r.height < 32 || r.width < 32) {
            const tag = el.tagName.toLowerCase();
            const txt = (el.innerText || el.getAttribute('aria-label') || '').slice(0, 40).replace(/\s+/g,' ');
            tiny.push({tag, txt, w: Math.round(r.width), h: Math.round(r.height)});
            if (tiny.length > 12) break;
        }
    }

    // text trop petit (< 12px)
    const smallText = [];
    const textNodes = document.querySelectorAll('p, span, a, li, label, h1, h2, h3, h4, h5, h6, button');
    for (const el of textNodes) {
        const txt = (el.innerText || '').trim();
        if (!txt || txt.length < 3) continue;
        const cs = window.getComputedStyle(el);
        const fs = parseFloat(cs.fontSize);
        if (fs < 12 && fs > 0) {
            smallText.push({tag: el.tagName.toLowerCase(), fs, txt: txt.slice(0,50)});
            if (smallText.length > 10) break;
        }
    }

    // images deformees / qui depassent
    const imgIssues = [];
    const imgs = document.querySelectorAll('img');
    for (const img of imgs) {
        const r = img.getBoundingClientRect();
        if (r.width === 0) continue;
        if (r.right > vw + 1) {
            imgIssues.push({src: img.src.slice(-60), w: Math.round(r.width), right: Math.round(r.right), reason: 'overflow'});
        }
        if (img.naturalWidth > 0) {
            const ratio = img.naturalWidth / img.naturalHeight;
            const drawn = r.width / r.height;
            if (Math.abs(ratio - drawn) > 0.15 && r.width > 100) {
                // imgIssues.push({src: img.src.slice(-60), reason: 'aspect', natural: ratio.toFixed(2), drawn: drawn.toFixed(2)});
            }
        }
    }

    // burger nav
    const burger = document.querySelector('[aria-label*="menu" i], button[aria-controls*="menu" i], header button');
    const burgerInfo = burger ? {
        present: true,
        tag: burger.tagName.toLowerCase(),
        text: (burger.innerText || burger.getAttribute('aria-label') || '').slice(0, 30),
        rect: burger.getBoundingClientRect(),
    } : { present: false };

    return {
        viewport: { vw, vh },
        overflowHorizontal,
        docScrollWidth,
        overflowing,
        tiny,
        smallText,
        imgIssues,
        burger: burgerInfo,
    };
}
"""

results = {}

with sync_playwright() as p:
    browser = p.chromium.launch()
    for vp_name, vw, vh in VIEWPORTS:
        ctx = browser.new_context(viewport={"width": vw, "height": vh}, device_scale_factor=1)
        page = ctx.new_page()
        for page_name, path in PAGES:
            url = BASE + path
            key = f"{page_name}__{vp_name}"
            print(f"== {key} -> {url}")
            try:
                page.goto(url, wait_until="networkidle", timeout=45000)
            except Exception as e:
                print(f"   load issue: {e}")
                try:
                    page.goto(url, wait_until="domcontentloaded", timeout=45000)
                except Exception as e2:
                    print(f"   second attempt failed: {e2}")
                    results[key] = {"error": str(e2)}
                    continue
            page.wait_for_timeout(1200)  # let reveal animations settle a bit
            # screenshot above-the-fold
            shot = os.path.join(OUT, f"{key}__atf.png")
            try:
                page.screenshot(path=shot, full_page=False)
            except Exception as e:
                print(f"   screenshot atf failed: {e}")
            # full page
            shot_full = os.path.join(OUT, f"{key}__full.png")
            try:
                page.screenshot(path=shot_full, full_page=True)
            except Exception as e:
                print(f"   screenshot full failed: {e}")
            try:
                data = page.evaluate(AUDIT_JS)
            except Exception as e:
                data = {"error": str(e)}
            results[key] = data

            # Si mobile, tester le burger
            if vp_name == "mobile-375":
                try:
                    # essayer de cliquer un eventuel burger
                    btn = page.locator('header button').first
                    if btn.count() > 0:
                        btn.click(timeout=3000)
                        page.wait_for_timeout(600)
                        burger_shot = os.path.join(OUT, f"{key}__burger-open.png")
                        page.screenshot(path=burger_shot, full_page=False)
                        results[key]["burger_clicked"] = True
                except Exception as e:
                    results[key]["burger_click_err"] = str(e)
        ctx.close()
    browser.close()

with open(os.path.join(OUT, "audit.json"), "w", encoding="utf-8") as f:
    json.dump(results, f, ensure_ascii=False, indent=2, default=str)

print("DONE -> audit.json")
