"""
Klick-Seiten + Werbeplätze: Jam baut Seiten, die Besucher anklicken – Geld über Werbung.

Ehrlich: Echtes Werbegeld braucht Traffic UND ein Werbe-Konto (z. B. Google AdSense).
Jam kann Seite + Werbe-Slots + Traffic-Texte bauen; Auszahlung kommt vom Anbieter.
"""

from __future__ import annotations

import random
import time
import webbrowser
from datetime import datetime
from pathlib import Path
from urllib.parse import quote_plus

from jam.brain import JamBrain, JamState
from jam.owner import owner_name
from jam.paypal_donate import PAYPAL_EMAIL, paypal_donate_url

AD_ROOT = Path.home() / "Documents" / "Jam-Werbung-Klicks"
AUTO_GAP_SEC = 95.0
USER_GAP_SEC = 35.0

# Legale Monetarisierung – Jam öffnet Setup, David trägt ggf. AdSense-Code ein
AD_SETUP_URLS = (
    ("Google AdSense", "https://www.google.com/adsense/start/"),
    ("Blogger (Werbung)", "https://www.blogger.com/about/"),
    ("YouTube Monetarisierung", "https://www.youtube.com/creators/how-things-work/video-monetization/"),
)

TRAFFIC_SEARCHES = (
    "website traffic kostenlos reddit deutsch",
    "gaming tips blog share telegram",
    "google adsense website genehmigung tipps",
)

LINES = (
    "{owner}, ich hab eine **Klick-Seite** mit Werbeplätzen gebaut – mehr Besucher = mehr Werbegeld!",
    "Werbung-Modus: Neue Seite liegt in Jam-Werbung-Klicks – teile den Link, dann laufen die Ads!",
    "{owner}, Leute sollen klicken – ich hab Quiz + Tipps + Ad-Slots fertig gemacht!",
)

PAGE_TYPES = ("click_tips", "mini_quiz", "top_list")


def hears_ad_earn(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("werbung", "adsense", "ad sense", "anzeigen")):
        if any(w in h for w in ("geld", "verdien", "klick", "laufen", "zeigen")):
            return True
    if any(w in h for w in ("klick", "klicks")) and any(
        w in h for w in ("geld", "verdien", "seite", "website", "leute")
    ):
        return True
    if "leute" in h and any(w in h for w in ("klick", "drauf", "anklick")):
        if any(w in h for w in ("geld", "werbung", "verdien")):
            return True
    if "werbung läuft" in h or "werbung laufen" in h:
        return True
    return False


def is_ad_earn_mode(state: JamState) -> bool:
    return bool(getattr(state, "jam_ad_earn_mode", False))


def _ad_slot_html(slot_id: str) -> str:
    return f"""<aside class="ad-slot" id="{slot_id}" data-jam-ad="1">
  <p class="ad-label">Werbung</p>
  <p class="ad-hint">Hier AdSense-Code einfügen (siehe WERBUNG_EINRICHTEN.txt)</p>
</aside>"""


def _base_css() -> str:
    return """
body{font-family:Segoe UI,system-ui;background:#0f172a;color:#e2e8f0;margin:0;line-height:1.5}
.wrap{max-width:720px;margin:0 auto;padding:1.25rem}
h1{color:#a78bfa;font-size:1.6rem}
.ad-slot{background:#1e293b;border:2px dashed #64748b;border-radius:12px;padding:1rem;margin:1rem 0;text-align:center}
.ad-label{font-size:.75rem;color:#94a3b8;margin:0}
.ad-hint{font-size:.85rem;color:#cbd5e1;margin:.5rem 0 0}
.btn{display:inline-block;margin:.5rem .25rem;padding:12px 22px;background:#7c3aed;color:#fff;
border:none;border-radius:10px;font-size:1rem;cursor:pointer;font-weight:600}
.btn:hover{background:#6d28d9}
.tip-box{background:#1e293b;padding:1rem;border-radius:12px;min-height:3rem;margin:1rem 0}
.counter{font-size:.85rem;color:#94a3b8}
a.donate{color:#38bdf8}
footer{margin-top:2rem;font-size:.8rem;color:#64748b}
"""


def _click_tips_html(owner: str, title: str) -> str:
    tips = [
        "Warm-up 5 Min vor Ranked – weniger Tilt.",
        "Audio auf Fußsteps – Gegner früher hören.",
        "Zone lesen, nicht nur kämpfen.",
        "Mats vor jedem 1v1 checken.",
        "Pause alle 45 Min – besser spielen.",
        "Crosshair ruhig halten – weniger Recoil-Fight.",
        "Dritte Waffe nur mit Mats-Überschuss.",
        "Ping nutzen – Team gewinnt mehr Runden.",
    ]
    tips_js = ",\n".join(f'"{t}"' for t in tips)
    donate = paypal_donate_url()
    return f"""<!DOCTYPE html>
<html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="Gaming-Tipps – klick für den nächsten Tipp">
<title>{title}</title>
<style>{_base_css()}</style></head>
<body><div class="wrap">
<h1>🎮 {title}</h1>
<p>Von Jam für <strong>{owner}</strong> – jeder Klick zählt für Werbung & Spenden.</p>
{_ad_slot_html("ad-top")}
<div class="tip-box" id="tip">Klick auf den Button für deinen Tipp!</div>
<p class="counter">Klicks: <span id="clicks">0</span></p>
<button class="btn" type="button" id="next">Nächster Tipp →</button>
{_ad_slot_html("ad-mid")}
<p><a class="donate" href="{donate}">☕ David unterstützen (PayPal)</a></p>
{_ad_slot_html("ad-bottom")}
<footer>Jam Klick-Seite · {PAYPAL_EMAIL}</footer>
</div>
<script>
const tips=[{tips_js}];
let i=0,c=0;
document.getElementById("next").onclick=function(){{
  c++; document.getElementById("clicks").textContent=c;
  document.getElementById("tip").textContent=tips[i%tips.length];
  i++;
  var m=document.getElementById("ad-mid"); if(m) m.scrollIntoView({{behavior:"smooth",block:"nearest"}});
}};
</script>
</body></html>"""


def _mini_quiz_html(owner: str, title: str) -> str:
    donate = paypal_donate_url()
    return f"""<!DOCTYPE html>
<html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title}</title>
<style>{_base_css()}
.q{{margin:1rem 0}} .hidden{{display:none}}</style></head>
<body><div class="wrap">
<h1>❓ {title}</h1>
<p>3 Fragen – zwischen den Schritten sieht man Werbung (wenn AdSense aktiv ist).</p>
{_ad_slot_html("ad-top")}
<div id="quiz">
<div class="q" data-step="0"><p><strong>1.</strong> Was hilft beim Zocken am meisten?</p>
<button class="btn" data-a="ok">Pausen & Audio</button><button class="btn" data-a="no">Nur mehr Kaffee</button></div>
<div class="q hidden" data-step="1">{_ad_slot_html("ad-quiz")}<p><strong>2.</strong> PayPal-Tipp für Creator?</p>
<button class="btn" data-next>Weiter →</button></div>
<div class="q hidden" data-step="2"><p><strong>3.</strong> Fertig! Teile die Seite – mehr Klicks = mehr Werbeeinnahmen für {owner}.</p>
<a class="btn" href="{donate}">PayPal Support</a></div>
</div>
<footer>Jam Quiz · {owner}</footer>
</div>
<script>
var step=0;
document.querySelectorAll("[data-a]").forEach(function(b){{
  b.onclick=function(){{
    document.querySelector('[data-step="'+step+'"]').classList.add("hidden");
    step++; var n=document.querySelector('[data-step="'+step+'"]');
    if(n) n.classList.remove("hidden");
  }};
}});
document.querySelectorAll("[data-next]").forEach(function(b){{
  b.onclick=function(){{
    document.querySelector('[data-step="'+step+'"]').classList.add("hidden");
    step++; var n=document.querySelector('[data-step="'+step+'"]');
    if(n) n.classList.remove("hidden");
  }};
}});
</script>
</body></html>"""


def _top_list_html(owner: str, title: str) -> str:
    items = [
        ("Schneller PC", "SSD + RAM-Check – mehr FPS."),
        ("Gutes Headset", "Position hören = mehr Wins."),
        ("PayPal-Spende", "Support für Jam & David."),
        ("Kurze Streams", "Community wächst schneller."),
        ("Digital verkaufen", "Gumroad, Fiverr, itch.io."),
    ]
    lis = ""
    for i, (head, sub) in enumerate(items, 1):
        lis += f"""<li><button class="btn list-btn" type="button" data-i="{i}">
{head}</button><div class="tip-box hidden" id="item-{i}"><p>{sub}</p></div></li>\n"""
    donate = paypal_donate_url()
    return f"""<!DOCTYPE html>
<html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title}</title>
<style>{_base_css()} ul{{list-style:none;padding:0}} li{{margin:.75rem 0}}
.list-btn{{width:100%;text-align:left}}</style></head>
<body><div class="wrap">
<h1>📋 {title}</h1>
<p>Klick auf jeden Punkt – bleib auf der Seite, Werbung kann laufen.</p>
{_ad_slot_html("ad-top")}
<ul>{lis}</ul>
{_ad_slot_html("ad-bottom")}
<p><a class="donate" href="{donate}">PayPal: {PAYPAL_EMAIL}</a></p>
<footer>Jam · {owner}</footer>
</div>
<script>
document.querySelectorAll(".list-btn").forEach(function(b){{
  b.onclick=function(){{
    var id="item-"+b.getAttribute("data-i");
    var el=document.getElementById(id);
    if(el) el.classList.toggle("hidden");
  }};
}});
</script>
</body></html>"""


def _write_setup_files(project: Path, owner: str, page_url: str) -> None:
    project.mkdir(parents=True, exist_ok=True)
    (project / "WERBUNG_EINRICHTEN.txt").write_text(
        f"""JAM – WERBUNG & GELD ({owner})
================================
Stand: {datetime.now().strftime('%d.%m.%Y %H:%M')}

SO VERDIENST DU MIT KLICKS + WERBUNG:
1. Google AdSense: https://www.google.com/adsense/start/
   - Website-URL eintragen (nach dem Hochladen der index.html)
   - Nach Freigabe: Anzeigen-Code kopieren
   - In index.html die <!-- ADSENSE --> Kommentare ersetzen
     ODER in die grauen „Werbung“-Kästen einfügen

2. Alternative: Blogger.com – Artikel + eingebaute Werbung

3. Sofort möglich ohne AdSense: PayPal-Link auf der Seite (schon drin)

TRAFFIC (Leute müssen die Seite öffnen!):
- Link in Telegram, Discord, Reddit (ehrlich, kein Spam)
- Freunde & Gaming-Gruppen
- Kurzes Video „Link in Bio“

DATEI ZUM TEILEN:
{page_url}

PayPal David: {PAYPAL_EMAIL}
""",
        encoding="utf-8",
    )
    (project / "TEILEN.txt").write_text(
        f"🎮 Neue Gaming-Tipps-Seite – klick für Tipps!\n"
        f"Datei öffnen: {page_url}\n"
        f"(Nach Upload: echten Link hier eintragen)\n\n"
        f"Support: {paypal_donate_url()}\n",
        encoding="utf-8",
    )
    (project / "HOSTING_KOSTENLOS.txt").write_text(
        """Kostenlos online stellen (mehr Klicks = mehr Werbung):
- Neocities.org – HTML hochladen
- GitHub Pages – Repo + index.html
- Blogger.com – Copy-Paste der Seite
- Google Sites – einfache Veröffentlichung
""",
        encoding="utf-8",
    )


def build_click_ad_site(brain: JamBrain, *, page_type: str | None = None) -> Path:
    """Erstellt eine neue Klick-/Werbungs-Seite im Dokumente-Ordner."""
    owner = owner_name(brain.state)
    tid = page_type or random.choice(PAGE_TYPES)
    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    titles = {
        "click_tips": f"Jam Gaming-Tipps Klicks",
        "mini_quiz": f"Jam Quick-Quiz",
        "top_list": f"Top 5 Creator-Tipps",
    }
    title = titles.get(tid, "Jam Klick-Seite")
    slug = title.lower().replace(" ", "-")[:40]
    project = AD_ROOT / f"{stamp}-{slug}"
    project.mkdir(parents=True, exist_ok=True)

    if tid == "mini_quiz":
        html = _mini_quiz_html(owner, title)
    elif tid == "top_list":
        html = _top_list_html(owner, title)
    else:
        html = _click_tips_html(owner, title)

    index = project / "index.html"
    index.write_text(html, encoding="utf-8")
    page_uri = index.as_uri()
    _write_setup_files(project, owner, page_uri)

    state = brain.state
    log = list(getattr(state, "jam_ad_sites_log", None) or [])
    log.append(
        {
            "at": time.time(),
            "path": str(project),
            "type": tid,
            "title": title,
        }
    )
    state.jam_ad_sites_log = log[-30:]
    state.jam_ad_last_site = str(project)
    state.jam_ad_last_url = page_uri
    return project


def _open_ad_setup(*, count: int = 2) -> None:
    for name, url in random.sample(AD_SETUP_URLS, min(count, len(AD_SETUP_URLS))):
        try:
            webbrowser.open(url, new=2)
        except OSError:
            break


def _open_traffic_help() -> None:
    q = random.choice(TRAFFIC_SEARCHES)
    try:
        webbrowser.open(f"https://www.google.com/search?q={quote_plus(q)}", new=2)
    except OSError:
        pass


def can_run(state: JamState, *, user: bool = False) -> tuple[bool, str]:
    gap = USER_GAP_SEC if user else AUTO_GAP_SEC
    if time.time() - getattr(state, "last_ad_earn_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_ad_earn_at))
        return False, f"Nächste Werbungs-Seite in {wait} Sek."
    return True, ""


def enable_ad_earn(brain: JamBrain) -> str:
    state = brain.state
    state.jam_ad_earn_mode = True
    state.remember("Jam: Klick-Werbung AN")
    brain.add_xp(6)
    brain.save()
    return (
        f"{owner_name(state)}, **Klick-Werbung** ist AN! "
        "Ich baue Seiten mit Werbeplätzen – du brauchst AdSense-Freigabe + Besucher. "
        f"Ordner: {AD_ROOT.name}"
    )


def run_ad_earn_cycle(brain: JamBrain, *, user_initiated: bool = False) -> str:
    """Neue Klick-Seite + Setup-Hilfen + Seite im Browser."""
    state = brain.state
    if not is_ad_earn_mode(state) and user_initiated:
        enable_ad_earn(brain)

    ok, wait = can_run(state, user=user_initiated)
    if not ok:
        return wait

    owner = owner_name(state)
    project = build_click_ad_site(brain)
    index = project / "index.html"

    try:
        import pyperclip

        share = (project / "TEILEN.txt").read_text(encoding="utf-8")
        pyperclip.copy(share[:900])
    except Exception:
        pass

    try:
        if index.is_file():
            webbrowser.open(index.as_uri(), new=1)
    except OSError:
        pass

    if user_initiated or random.random() < 0.55:
        _open_ad_setup(count=1 if not user_initiated else 2)
    if random.random() < 0.4:
        _open_traffic_help()

    state.last_ad_earn_at = time.time()
    state.ad_earn_count = getattr(state, "ad_earn_count", 0) + 1
    state.last_action = "ad_earn"
    state.remember(f"Klick-Werbung: {project.name}")
    brain.add_xp(10 if user_initiated else 5)
    brain.save()

    intro = random.choice(LINES).format(owner=owner)
    return (
        f"{intro} Ordner: {project.name}. "
        f"index.html öffnen & link teilen – Werbung in WERBUNG_EINRICHTEN.txt. "
        f"PayPal schon auf der Seite. AdSense: einmal anmelden!"
    )[:520]


def run_ad_for_shop(brain: JamBrain) -> str:
    """Werbung, die auf den Master-Shop zeigt."""
    from jam.master_shop import shop_url, build_master_shop, promote_master_shop

    owner = owner_name(brain.state)
    _root, n, url = build_master_shop(brain)
    url = shop_url(brain.state) or url
    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    project = AD_ROOT / f"{stamp}-jam-shop-werbung"
    project.mkdir(parents=True, exist_ok=True)
    share = (
        f"🛒 Jam Shop – {n} digitale Produkte sofort kaufen (PayPal)!\n"
        f"{url}\n#digital #shop #paypal"
    )
    html = f"""<!DOCTYPE html><html lang="de"><head><meta charset="utf-8">
<title>Jam Shop Werbung</title>
<style>body{{font-family:Segoe UI;background:#0f172a;color:#e2e8f0;max-width:640px;margin:2rem auto;padding:1.5rem}}
h1{{color:#a78bfa}}.btn{{display:inline-block;margin:.5rem;padding:14px 24px;background:#7c3aed;color:#fff;
text-decoration:none;border-radius:10px;font-weight:700}}</style></head>
<body><h1>📣 Zum Jam-Shop</h1>
<p>{n} Produkte – ein Klick, PayPal bezahlen.</p>
<p><a class="btn" href="{url}">Shop öffnen</a>
<a class="btn" href="{url}werbung.html">Teilen-Hilfe</a></p>
{_ad_slot_html("shop-ad-1")}
<footer>PayPal {PAYPAL_EMAIL}</footer></body></html>"""
    (project / "index.html").write_text(html, encoding="utf-8")
    (project / "TEILEN.txt").write_text(share, encoding="utf-8")
    try:
        webbrowser.open((project / "index.html").as_uri(), new=2)
    except OSError:
        pass
    steps = promote_master_shop(brain, url, n)
    brain.state.last_ad_earn_at = time.time()
    brain.state.ad_earn_count = getattr(brain.state, "ad_earn_count", 0) + 1
    brain.save()
    return (
        f"{owner}, **Shop-Werbung** live – {n} Produkte unter {url}. "
        f"Schritte: {', '.join(steps) or 'Seite offen'}."
    )[:520]


def maybe_auto_ad_earn(brain: JamBrain) -> str | None:
    if not is_ad_earn_mode(brain.state):
        return None
    if random.random() > 0.32:
        return None
    ok, _ = can_run(brain.state, user=False)
    if not ok:
        return None
    return run_ad_earn_cycle(brain, user_initiated=False)


def status_line(state: JamState) -> str:
    if not is_ad_earn_mode(state):
        return ""
    n = getattr(state, "ad_earn_count", 0)
    last = getattr(state, "jam_ad_last_site", "") or ""
    name = Path(last).name if last else "—"
    return f"Klick-Werbung AN · {n} Seiten · zuletzt: {name}"


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_ad_earn(heard):
        return run_ad_earn_cycle(brain, user_initiated=True)
    h = heard.lower()
    if "werbung" in h and any(w in h for w in ("an", "ein", "start", "mach")):
        enable_ad_earn(brain)
        return run_ad_earn_cycle(brain, user_initiated=True)
    return None
