#!/usr/bin/env python3
"""Cari elemen yang membuat studiosoft.id melebar di layar ponsel (penyebab perlu zoom out).
Ukur: scrollWidth vs innerWidth, lalu daftar elemen yang melewati lebar layar."""
from playwright.sync_api import sync_playwright
import json

URL = "https://studiosoft.id/"
JS = """
() => {
  const vw = window.innerWidth;
  const de = document.documentElement;
  const hasil = [];
  document.querySelectorAll('*').forEach(el => {
    const r = el.getBoundingClientRect();
    const lebar = Math.round(r.width);
    const kanan = Math.round(r.right);
    if (lebar > vw + 2 || kanan > vw + 2) {
      const gaya = getComputedStyle(el);
      // bikin jalur singkat: tag.class (30 char pertama)
      let cls = (el.className && typeof el.className === 'string') ? el.className.trim().split(/\\s+/).slice(0,3).join('.') : '';
      hasil.push({
        tag: el.tagName.toLowerCase(),
        cls: cls.slice(0, 70),
        id: el.id || '',
        width: lebar,
        right: kanan,
        overflow: kanan - vw,
        posisi: gaya.position,
        display: gaya.display,
        minWidth: gaya.minWidth,
        maxWidth: gaya.maxWidth,
        overflowX: gaya.overflowX,
        teks: (el.textContent || '').trim().slice(0, 60)
      });
    }
  });
  hasil.sort((a,b) => b.overflow - a.overflow);
  return {
    innerWidth: vw,
    scrollWidth: de.scrollWidth,
    bodyScrollWidth: document.body.scrollWidth,
    lebihLebar: de.scrollWidth - vw,
    jumlahPelanggar: hasil.length,
    pelanggar: hasil.slice(0, 22)
  };
}
"""

with sync_playwright() as p:
    b = p.chromium.launch(args=["--no-sandbox", "--disable-dev-shm-usage"])
    for nama, w, h in (("iPhone 390px", 390, 844), ("Android kecil 360px", 360, 800)):
        ctx = b.new_context(viewport={"width": w, "height": h}, device_scale_factor=2,
                            is_mobile=True, has_touch=True,
                            user_agent=("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
                                        "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"))
        pg = ctx.new_page()
        pg.goto(URL, wait_until="domcontentloaded", timeout=90000)
        pg.wait_for_timeout(4000)
        d = pg.evaluate(JS)
        print(f"\n=========== {nama} ===========")
        print(f"  lebar layar  : {d['innerWidth']}px")
        print(f"  scrollWidth  : {d['scrollWidth']}px  → KELEBIHAN {d['lebihLebar']}px")
        print(f"  body         : {d['bodyScrollWidth']}px")
        print(f"  elemen melebar: {d['jumlahPelanggar']}")
        for i, e in enumerate(d["pelanggar"], 1):
            print(f"   {i:>2}. +{e['overflow']:>4}px | {e['width']:>4}px lebar | <{e['tag']}"
                  f"{('.' + e['cls']) if e['cls'] else ''}{('#' + e['id']) if e['id'] else ''}>")
            print(f"       posisi={e['posisi']} display={e['display']} overflowX={e['overflowX']} "
                  f"minW={e['minWidth']} maxW={e['maxWidth']}")
            if e["teks"]:
                print(f"       teks: {e['teks']!r}")
        pg.screenshot(path=f"ss_mobile_{w}.png", full_page=False)
        ctx.close()
    b.close()
print("\nscreenshot: ss_mobile_390.png, ss_mobile_360.png")
