#!/usr/bin/env python3
"""Cari aturan CSS yang memaksa lebar widget Trustindex, lalu uji perbaikan dengan gaya terpaksa.
Juga periksa opsi setelan plugin (data-* atribut) yang menentukan lebar."""
from playwright.sync_api import sync_playwright

URL = "https://studiosoft.id/"

CEK_ATURAN = """() => {
  const hasil = {inline: [], aturan: [], atribut: {}};
  const w = document.querySelector('.ti-widget');
  if (!w) return {error: 'widget tidak ada'};
  hasil.inline.push('style="' + (w.getAttribute('style') || '') + '"');
  hasil.atribut.class = w.className;
  for (const a of w.attributes) {
    if (a.name.startsWith('data-')) hasil.atribut[a.name] = a.value.slice(0, 90);
  }
  // aturan CSS yang menyebut .ti-widget dan memuat width
  for (const ss of document.styleSheets) {
    let rules;
    try { rules = ss.cssRules; } catch (e) { continue; }
    if (!rules) continue;
    for (const r of rules) {
      const t = r.cssText || '';
      if (t.includes('.ti-widget') && /width/.test(t) && t.length < 400) {
        hasil.aturan.push(t.replace(/\\s+/g, ' ').slice(0, 240));
      }
      if (r.cssRules) {
        for (const r2 of r.cssRules) {
          const t2 = r2.cssText || '';
          if (t2.includes('.ti-widget') && /width/.test(t2) && t2.length < 400) {
            hasil.aturan.push('@media → ' + t2.replace(/\\s+/g, ' ').slice(0, 220));
          }
        }
      }
    }
  }
  hasil.jumlahAturan = hasil.aturan.length;
  hasil.aturan = hasil.aturan.slice(0, 12);
  return hasil;
}"""

UJI = """(mode) => {
  const imp = (el, prop, val) => el && el.style.setProperty(prop, val, 'important');
  const w = document.querySelector('.ti-widget');
  const pre = w ? w.closest('pre') : null;
  const rantai = [];
  if (w) { let e = w; let n = 0; while (e && e.tagName !== 'BODY' && n < 8) { rantai.push(e); e = e.parentElement; n++; } }
  if (mode === 'A') {                       // widget sendiri dibatasi + kliping
    imp(w, 'width', '100%'); imp(w, 'max-width', '100%'); imp(w, 'overflow', 'hidden');
  } else if (mode === 'B') {                // A + pembungkus <pre> dinetralkan
    imp(w, 'width', '100%'); imp(w, 'max-width', '100%'); imp(w, 'overflow', 'hidden');
    imp(pre, 'white-space', 'normal'); imp(pre, 'max-width', '100%'); imp(pre, 'overflow', 'hidden');
  } else if (mode === 'C') {                // B + semua induk diklip
    imp(w, 'width', '100%'); imp(w, 'max-width', '100%'); imp(w, 'overflow', 'hidden');
    imp(pre, 'white-space', 'normal'); imp(pre, 'max-width', '100%');
    rantai.slice(1).forEach(e => { imp(e, 'max-width', '100%'); imp(e, 'overflow-x', 'hidden'); });
  } else if (mode === 'D') {                // C + isi slider dibereskan
    imp(w, 'width', '100%'); imp(w, 'max-width', '100%'); imp(w, 'overflow', 'hidden');
    imp(pre, 'white-space', 'normal'); imp(pre, 'max-width', '100%');
    rantai.slice(1).forEach(e => { imp(e, 'max-width', '100%'); imp(e, 'overflow-x', 'hidden'); });
    const wrap = document.querySelector('.ti-reviews-container-wrapper');
    imp(wrap, 'max-width', '100%'); imp(wrap, 'width', '100%'); imp(wrap, 'overflow-x', 'auto');
    document.querySelectorAll('.ti-review-item').forEach(el => { imp(el, 'max-width', '100%'); });
  }
  const de = document.documentElement;
  return {
    scrollWidth: de.scrollWidth, innerWidth: window.innerWidth, lebih: de.scrollWidth - window.innerWidth,
    lebarWidget: w ? Math.round(w.getBoundingClientRect().width) : null,
    jumlahUlasan: document.querySelectorAll('.ti-review-item').length,
    teksTerlihat: (w ? (w.textContent || '').trim().length : 0)
  };
}"""

with sync_playwright() as p:
    b = p.chromium.launch(args=["--no-sandbox", "--disable-dev-shm-usage"])
    ctx = b.new_context(viewport={"width": 390, "height": 844}, device_scale_factor=2, is_mobile=True, has_touch=True)
    pg = ctx.new_page()
    pg.goto(URL, wait_until="domcontentloaded", timeout=90000)
    pg.wait_for_timeout(5000)

    info = pg.evaluate(CEK_ATURAN)
    print("=== atribut & gaya widget ===")
    for k, v in (info.get("atribut") or {}).items():
        if k.startswith("data-") and ("width" in k or "layout" in k or "columns" in k or "col" in k or "mobile" in k or "desktop" in k):
            print(f"   {k:<28} {v}")
    print(f"   inline style: {info['inline']}")
    print(f"\n=== {info.get('jumlahAturan',0)} aturan CSS memaksa lebar (contoh) ===")
    for a in info.get("aturan", []):
        print("   ", a)

    print("\n=== hasil uji perbaikan (gaya dipaksa !important lewat JS) ===")
    for mode in ("A", "B", "C", "D"):
        d = pg.evaluate(UJI, mode)
        tanda = "✅ PAS" if d["lebih"] <= 2 else "❌ masih melebar"
        print(f"   mode {mode}: scrollWidth {d['scrollWidth']}px (kelebihan {d['lebih']}px) | "
              f"widget {d['lebarWidget']}px | ulasan {d['jumlahUlasan']} | {tanda}")
    ctx.close()
    b.close()
