#!/usr/bin/env python3
"""Telusuri lebih dalam: meta viewport yang dilihat browser, lebar layout sesungguhnya,
dan rantai induk elemen Trustindex yang melebar di studiosoft.id."""
from playwright.sync_api import sync_playwright

URL = "https://studiosoft.id/"
JS = """
() => {
  const de = document.documentElement;
  const meta = document.querySelector('meta[name=viewport]');
  const out = {
    metaViewport: meta ? meta.getAttribute('content') : '(TIDAK ADA)',
    innerWidth: window.innerWidth,
    clientWidth: de.clientWidth,
    scrollWidth: de.scrollWidth,
    visualWidth: window.visualViewport ? Math.round(window.visualViewport.width) : null,
    visualScale: window.visualViewport ? window.visualViewport.scale : null,
    screenWidth: screen.width,
    dpr: window.devicePixelRatio,
    rantai: []
  };
  // cari elemen ti-* terlebar lalu telusuri induknya sampai body
  let target = null, maxW = 0;
  document.querySelectorAll('[class*="ti-"]').forEach(el => {
    const w = el.getBoundingClientRect().width;
    if (w > maxW) { maxW = w; target = el; }
  });
  if (!target) return out;
  out.elemenTerlebar = { cls: String(target.className).slice(0,80), width: Math.round(maxW) };
  let el = target, n = 0;
  while (el && el.tagName !== 'HTML' && n < 14) {
    const r = el.getBoundingClientRect();
    const s = getComputedStyle(el);
    out.rantai.push({
      tag: el.tagName.toLowerCase(),
      cls: String(el.className || '').slice(0, 60),
      id: el.id || '',
      width: Math.round(r.width),
      maxWidth: s.maxWidth,
      overflowX: s.overflowX,
      display: s.display,
      position: s.position,
      parent: el.parentElement ? el.parentElement.tagName.toLowerCase() : '-'
    });
    el = el.parentElement; n++;
  }
  // apakah widget ini di dalam iframe?
  out.adaIframeTrustindex = !!document.querySelector('iframe[src*="trustindex"], iframe[title*="review" i]');
  out.jumlahNodeTi = document.querySelectorAll('[class*="ti-"]').length;
  return out;
}
"""

with sync_playwright() as p:
    b = p.chromium.launch(args=["--no-sandbox", "--disable-dev-shm-usage"])
    for nama, w, h, mob in (("iPhone 390 (is_mobile)", 390, 844, True), ("iPhone 390 (desktop-mode)", 390, 844, False)):
        ctx = b.new_context(viewport={"width": w, "height": h}, device_scale_factor=2, is_mobile=mob, has_touch=mob)
        pg = ctx.new_page()
        pg.goto(URL, wait_until="domcontentloaded", timeout=90000)
        pg.wait_for_timeout(5000)
        d = pg.evaluate(JS)
        print(f"\n================ {nama} ================")
        for k in ("metaViewport", "innerWidth", "clientWidth", "scrollWidth", "visualWidth",
                  "visualScale", "screenWidth", "dpr", "adaIframeTrustindex", "jumlahNodeTi"):
            print(f"  {k:<20}: {d.get(k)}")
        if d.get("elemenTerlebar"):
            print(f"  elemen terlebar      : {d['elemenTerlebar']['width']}px  {d['elemenTerlebar']['cls']}")
        print("  rantai induk:")
        for i, r in enumerate(d["rantai"], 1):
            print(f"   {i:>2}. <{r['tag']}{('.' + r['cls']) if r['cls'] else ''}{('#' + r['id']) if r['id'] else ''}>".ljust(72)
                  + f" {r['width']:>5}px  maxW={r['maxWidth']:<8} overflowX={r['overflowX']:<8} display={r['display']}")
        ctx.close()
    b.close()
