"""
Hilfen für Jam Browser (WebEngine): Cookie-Banner wegklicken, Login ausfüllen.

Nur normale Web-Dialoge – kein CAPTCHA-/2FA-Umgehen.
"""

from __future__ import annotations

import json


def js_assist_page(email: str, password: str) -> str:
    """JavaScript, das nach Seitenladung Consent + Login versucht."""
    em = json.dumps(email)
    pw = json.dumps(password)
    return f"""
(function() {{
  var email = {em}, password = {pw}, steps = [];
  var consentWords = [
    'accept all', 'alle akzeptieren', 'akzeptieren', 'accept', 'agree',
    'zustimmen', 'allow all', 'einverstanden', 'i agree', 'got it', 'ok'
  ];
  function clickMatch(el) {{
    try {{
      var t = ((el.innerText || el.textContent || el.value || '') + '').trim().toLowerCase();
      if (!t || t.length > 48) return false;
      for (var i = 0; i < consentWords.length; i++) {{
        if (t === consentWords[i] || t.indexOf(consentWords[i]) === 0) {{
          el.click(); return true;
        }}
      }}
    }} catch (e) {{}}
    return false;
  }}
  document.querySelectorAll('button, a, input[type="button"], input[type="submit"]').forEach(function(el) {{
    if (clickMatch(el)) steps.push('consent');
  }});
  var emailSels = [
    'input[type="email"]', 'input[name*="email" i]', 'input[id*="email" i]',
    'input[autocomplete="email"]', 'input[placeholder*="mail" i]'
  ];
  for (var s = 0; s < emailSels.length; s++) {{
    var el = document.querySelector(emailSels[s]);
    if (el && !el.value) {{ el.focus(); el.value = email; el.dispatchEvent(new Event('input', {{bubbles:true}})); steps.push('email'); break; }}
  }}
  var pwdSels = ['input[type="password"]', 'input[name*="password" i]', 'input[id*="password" i]'];
  for (var p = 0; p < pwdSels.length; p++) {{
    var pe = document.querySelector(pwdSels[p]);
    if (pe && !pe.value) {{ pe.focus(); pe.value = password; pe.dispatchEvent(new Event('input', {{bubbles:true}})); steps.push('password'); break; }}
  }}
  var btnWords = ['sign up', 'signup', 'register', 'registrieren', 'weiter', 'continue', 'log in', 'login', 'anmelden', 'next'];
  document.querySelectorAll('button, input[type="submit"], a[role="button"]').forEach(function(el) {{
    var t = ((el.innerText || el.value || '') + '').trim().toLowerCase();
    for (var b = 0; b < btnWords.length; b++) {{
      if (t.indexOf(btnWords[b]) >= 0 && t.length < 32) {{
        try {{ el.click(); steps.push('btn:' + btnWords[b]); }} catch (e) {{}}
        return;
      }}
    }}
  }});
  return JSON.stringify(steps);
}})();
"""


def parse_js_result(raw) -> list[str]:
    if raw is None:
        return []
    try:
        if isinstance(raw, str):
            data = json.loads(raw)
        else:
            data = raw
        return list(data) if isinstance(data, list) else []
    except (json.JSONDecodeError, TypeError):
        return []
