"""
VidPuls – Landingpage für Cloudflare Pages (vidpuls.de).

Baut statische Seite nach Documents/VidPuls.
"""

from __future__ import annotations

import json
import os
from pathlib import Path

SITE_ROOT = Path.home() / "Documents" / "VidPuls"
STUDIO_PORT = 8791


def _site_url(explicit: str | None = None) -> str:
    if explicit:
        return explicit.rstrip("/")
    for key in ("VIDPULS_SITE_URL", "CLIPWELLE_SITE_URL", "JAMPULSE_SITE_URL"):
        val = os.environ.get(key, "").strip()
        if val:
            return val.rstrip("/")
    for name in ("vidpuls-config.json", "clipwelle-config.json"):
        cfg = Path(__file__).resolve().parents[1] / "data" / name
        if cfg.is_file():
            try:
                data = json.loads(cfg.read_text(encoding="utf-8"))
                return str(data.get("site_url") or "").rstrip("/")
            except (json.JSONDecodeError, OSError):
                pass
    from jam.jampulse_brand import PRODUCT_SITE_URL

    return PRODUCT_SITE_URL.rstrip("/")


def _landing_html(*, site_url: str, studio_url: str) -> str:
    from jam.jampulse_brand import MINUTE_OFFER, PRODUCT_BRAND, PRODUCT_TAGLINE, SINGLE_VIDEO_OFFER, SUBSCRIPTION_OFFER
    from jam.jampulse_checkout import product_catalog
    from jam.jampulse_payments import enrich_catalog, payment_methods_summary, sepa_info
    from jam.vidpuls_showcase import load_manifest, showcase_css, showcase_html

    products = enrich_catalog(product_catalog())
    sub = SUBSCRIPTION_OFFER
    monthly = products.get("pro_monthly") or {}
    yearly = products.get("pro_yearly") or {}
    m_price = f"{float(monthly.get('price_eur', sub['monthly_eur'])):.2f}".replace(".", ",")
    y_price = f"{float(yearly.get('price_eur', sub['yearly_eur'])):.2f}".replace(".", ",")
    m_paypal = monthly.get("paypal_url") or "#"
    y_paypal = yearly.get("paypal_url") or "#"
    single = products.get("video_1") or {}
    s_price = f"{float(single.get('price_eur', SINGLE_VIDEO_OFFER['price_eur'])):.2f}".replace(".", ",")
    s_paypal = single.get("paypal_url") or "#"
    tiers_html = f"""
        <div class="tier">
          <div><strong>Gratis</strong><br><span class="note">1 Video mit VidPuls-Wasserzeichen · 60–120 Sek.</span></div>
          <div class="price">0 €</div>
          <div class="btns"><a class="btn primary" href="{studio_url}">Im Studio starten</a></div>
        </div>
        <div class="tier">
          <div><strong>1 Video ohne Wasserzeichen</strong><br><span class="note">Einmalzahlung · volle Qualität</span></div>
          <div class="price">{s_price} €</div>
          <div class="btns">
            <button type="button" class="btn stripe" data-pid="video_1">Stripe · Karte · Klarna</button>
            <a class="btn ghost" href="{s_paypal}" target="_blank" rel="noopener">PayPal</a>
          </div>
        </div>
        <div class="tier">
          <div><strong>VidPuls Pro · Monat</strong><br><span class="note">Monatlich kündbar · unbegrenzt Videos</span></div>
          <div class="price">{m_price} €/Mo</div>
          <div class="btns">
            <button type="button" class="btn stripe" data-pid="pro_monthly">Stripe · Karte · Klarna</button>
            <a class="btn ghost" href="{m_paypal}" target="_blank" rel="noopener">PayPal</a>
          </div>
        </div>
        <div class="tier">
          <div><strong>VidPuls Pro · Jahr</strong><br><span class="note">{sub.get('price_note', '')}</span></div>
          <div class="price">{y_price} €/Jahr</div>
          <div class="btns">
            <button type="button" class="btn stripe" data-pid="pro_yearly">Stripe · Karte · Klarna</button>
            <a class="btn ghost" href="{y_paypal}" target="_blank" rel="noopener">PayPal</a>
          </div>
        </div>"""

    methods = " · ".join(payment_methods_summary()[:6])
    sepa = sepa_info()
    sepa_block = ""
    if sepa:
        sepa_block = f"""
        <p class="note"><strong>Überweisung:</strong> {sepa['holder']} · IBAN {sepa['iban']}
        {(' · BIC ' + sepa['bic']) if sepa.get('bic') else ''}<br>{sepa['note']}</p>"""

    includes = "".join(f"<li>{x}</li>" for x in MINUTE_OFFER.get("includes", [])[:5])
    from jam.jami_promo_banner import jami_promo_banner_css, jami_promo_banner_html, jami_promo_banner_script

    jami_banner = jami_promo_banner_html(variant="wide", utm_source="vidpuls", utm_medium="landing")
    jami_css = jami_promo_banner_css(variant="wide")
    jami_script = jami_promo_banner_script()
    from jam.clipwelle_legal import legal_footer_links

    legal_foot = legal_footer_links(prefix="")

    hero_inner = f"""<h1>{PRODUCT_BRAND}</h1>
  <p>{PRODUCT_TAGLINE}</p>
  <p>Promo-Videos <strong>60–120 Sek.</strong> · bis <strong>4K</strong> · Auto-Post TikTok &amp; YouTube</p>
  <div class="cta">
    <a class="btn primary" href="{studio_url}">Studio öffnen</a>
    <a class="btn ghost" href="#preise">Preise</a>
  </div>"""
    showcase_block = showcase_html(manifest=load_manifest(), hero_inner=hero_inner)

    return f"""<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>{PRODUCT_BRAND} – KI Promo-Videos ab 19,99 €/Monat</title>
<meta name="description" content="{PRODUCT_TAGLINE} 60–120 Sek., 4K, Auto-Post TikTok & YouTube. VidPuls Pro ab 19,99 €/Monat."/>
<meta property="og:title" content="{PRODUCT_BRAND} – KI Video in 1 Minute"/>
<meta property="og:description" content="{PRODUCT_TAGLINE}"/>
<meta property="og:url" content="{site_url}/"/>
<style>
:root {{
  --bg:#050508;--panel:#12101a;--line:rgba(255,255,255,.1);--text:#f4f0ff;--muted:#9ca3af;
  --accent:#a855f7;--mint:#34d399;--pink:#ec4899;
}}
* {{ box-sizing:border-box; }}
body {{ margin:0; font-family:Segoe UI,system-ui,sans-serif; background:var(--bg); color:var(--text); line-height:1.55; }}
.hero {{ padding:0; text-align:center; }}
.hero h1 {{ font-size:clamp(2rem,6vw,3rem); margin:0 0 .5rem; background:linear-gradient(135deg,var(--accent),var(--pink)); -webkit-background-clip:text; color:transparent; }}
.hero p {{ color:var(--muted); font-size:1.05rem; }}
{showcase_css()}
.cta {{ display:flex; gap:.75rem; justify-content:center; flex-wrap:wrap; margin:1.5rem 0; }}
.btn {{ display:inline-block; padding:.75rem 1.25rem; border-radius:999px; border:none; cursor:pointer; font-weight:600; text-decoration:none; font-size:.95rem; }}
.btn.primary {{ background:linear-gradient(135deg,var(--accent),var(--pink)); color:#fff; }}
.btn.ghost {{ background:transparent; border:1px solid var(--line); color:var(--text); }}
.btn.stripe {{ background:var(--mint); color:#041; border:none; }}
section {{ max-width:880px; margin:0 auto; padding:1rem 1.25rem 2rem; }}
.card {{ background:var(--panel); border:1px solid var(--line); border-radius:16px; padding:1.25rem; margin-bottom:1rem; }}
.card h2 {{ margin:0 0 .75rem; font-size:1.15rem; }}
.tier {{ display:grid; grid-template-columns:1fr auto; gap:.5rem 1rem; align-items:center; padding:.75rem 0; border-bottom:1px solid var(--line); }}
.tier:last-child {{ border-bottom:none; }}
.price {{ font-size:1.2rem; font-weight:700; color:var(--mint); }}
.btns {{ grid-column:1/-1; display:flex; gap:.5rem; flex-wrap:wrap; }}
ul {{ margin:.5rem 0; padding-left:1.2rem; color:var(--muted); }}
.note {{ font-size:.85rem; color:var(--muted); }}
footer {{ text-align:center; padding:2rem; color:var(--muted); font-size:.82rem; }}
footer a {{ color:var(--muted); text-decoration:none; }}
footer a:hover {{ color:var(--accent); }}
{jami_css}
</style>
</head>
<body>
<header class="hero">
{showcase_block}
</header>

{jami_banner}

<section class="card">
  <h2>Was du bekommst</h2>
  <ul>{includes}</ul>
  <p class="note">{MINUTE_OFFER.get('price_note', '')}</p>
</section>

<section id="preise" class="card">
  <h2>Preise</h2>
  <p class="note" style="margin-bottom:1rem">Gratis mit Wasserzeichen · ohne Wasserzeichen ab {s_price} €/Video oder Pro-Abo</p>
  {tiers_html}
  <p class="note" style="margin-top:1rem"><strong>Zahlungsarten:</strong> {methods}</p>
  {sepa_block}
</section>

<section class="card">
  <h2>So geht's</h2>
  <ol style="color:var(--muted)">
    <li>Prompt eingeben oder Branchen-Vorlage wählen</li>
    <li>Video rendern (1–2 Min., Voiceover inklusive)</li>
    <li>Auto-Post: TikTok + YouTube Upload vorbereitet</li>
  </ol>
  <div class="cta"><a class="btn primary" href="{studio_url}">Jetzt starten</a></div>
</section>

<footer>
  <p>{PRODUCT_BRAND} · ein Produkt von KI Web Studio · <a href="mailto:kontakt@ki-web-studio.de" style="color:var(--accent)">kontakt@ki-web-studio.de</a></p>
  <p style="margin-top:.5rem">{legal_foot}</p>
</footer>

<script>
const API = '/api/vidpuls/checkout';
document.querySelectorAll('.btn.stripe[data-pid]').forEach(btn => {{
  btn.onclick = async () => {{
    btn.disabled = true;
    try {{
      const r = await fetch(API, {{
        method: 'POST',
        headers: {{ 'Content-Type': 'application/json' }},
        body: JSON.stringify({{ productId: btn.dataset.pid }})
      }});
      const j = await r.json();
      if (j.url) location.href = j.url;
      else alert(j.error || 'Checkout fehlgeschlagen');
    }} catch (e) {{
      alert('Netzwerkfehler – später erneut versuchen');
    }} finally {{
      btn.disabled = false;
    }}
  }};
}});
{jami_script}
</script>
</body>
</html>"""


def _danke_html(*, site_url: str, studio_url: str) -> str:
    from jam.clipwelle_legal import legal_footer_links
    from jam.jampulse_brand import PRODUCT_BRAND

    legal_foot = legal_footer_links(prefix="")

    return f"""<!DOCTYPE html>
<html lang="de">
<head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>{PRODUCT_BRAND} – Danke</title>
<style>
body {{ font-family:Segoe UI,sans-serif; background:#050508; color:#eee; padding:2rem; text-align:center; }}
a {{ color:#a855f7; }}
</style></head>
<body>
<h1>{PRODUCT_BRAND}</h1>
<p id="msg">Zahlung wird geprüft…</p>
<p><a href="{studio_url}">Zum Studio</a> · <a href="{site_url}/">Startseite</a></p>
<p style="margin-top:1rem;font-size:.82rem;opacity:.75">{legal_foot}</p>
<script>
(async () => {{
  const q = new URLSearchParams(location.search);
  const sid = q.get('session_id');
  if (!sid) {{
    document.getElementById('msg').textContent = 'Danke! Bei PayPal-Überweisung: E-Mail an kontakt@ki-web-studio.de – Freischaltung in 24 h.';
    return;
  }}
  try {{
    const r = await fetch('/api/vidpuls/verify?session_id=' + encodeURIComponent(sid));
    const j = await r.json();
    document.getElementById('msg').textContent = j.ok
      ? 'Zahlung OK – ' + (j.productId || '') + '. Studio öffnen und loslegen!'
      : (j.error || 'Zahlung noch nicht abgeschlossen');
  }} catch (_) {{
    document.getElementById('msg').textContent = 'Danke! Freischaltung erfolgt automatisch.';
  }}
}})();
</script>
</body></html>"""


def build_site(*, site_url: str | None = None, studio_url: str | None = None) -> Path:
    resolved = _site_url(site_url)
    studio = (studio_url or f"http://127.0.0.1:{STUDIO_PORT}").rstrip("/")
    SITE_ROOT.mkdir(parents=True, exist_ok=True)

    (SITE_ROOT / "index.html").write_text(
        _landing_html(site_url=resolved, studio_url=studio),
        encoding="utf-8",
    )
    (SITE_ROOT / "danke.html").write_text(
        _danke_html(site_url=resolved, studio_url=studio),
        encoding="utf-8",
    )
    (SITE_ROOT / "js").mkdir(exist_ok=True)
    (SITE_ROOT / "js" / "config.json").write_text(
        json.dumps({"siteUrl": resolved, "studioUrl": studio, "brand": "VidPuls"}, indent=2),
        encoding="utf-8",
    )
    from jam.clipwelle_legal import write_legal_pages
    from jam.vidpuls_showcase import sync_showcase_to_site

    sync_showcase_to_site(SITE_ROOT)
    write_legal_pages(SITE_ROOT, site_url=resolved)
    return SITE_ROOT
