"""Dialog Studio – Werbetexte, Feature-Liste, Jami-Dating Sidebar."""

from __future__ import annotations

import json
from pathlib import Path

from jam.jampulse_brand import MINUTE_OFFER, PRODUCT_BRAND
from jam.jami_promo_banner import (
    JAMI_SITE_URL,
    jami_promo_banner_css,
    jami_promo_banner_html,
    jami_promo_banner_script,
    jami_signup_url,
)

# Dialog-Videos: Länge folgt dem Skript (typisch Promo 30–120 s)
DIALOG_MAX_SEC = 120


def program_features() -> list[dict[str, str]]:
    """Was VidPuls / Dialog Studio kann – für UI & Werbung."""
    minute = MINUTE_OFFER
    return [
        {
            "icon": "🎬",
            "title": "Videos bis 2 Minuten",
            "text": (
                f"Promo-Videos {minute['duration_min_sec']}–{minute['duration_max_sec']} Sek. "
                f"· Dialog-Studio bis ~{DIALOG_MAX_SEC} Sek. (je nach Textlänge)"
            ),
        },
        {
            "icon": "👥",
            "title": "3D-Figuren + Lip-Sync",
            "text": "Sarah & Laura · Rhubarb Lip-Sync · Mimik, Gesten, Blickkontakt",
        },
        {
            "icon": "🔊",
            "title": "KI-Stimmen",
            "text": "ElevenLabs (deutsch) · Fallback Edge TTS · zwei Sprecher wählbar",
        },
        {
            "icon": "📱",
            "title": "9:16 für TikTok & Reels",
            "text": "1080p oder 4K · MP4 fertig zum Posten · Caption & Hashtags",
        },
        {
            "icon": "🏠",
            "title": "WLAN für Freunde",
            "text": "Zeitpass im heimischen Netz teilen · PayPal & Überweisung",
        },
        {
            "icon": "💜",
            "title": "Jami-Dating Promo",
            "text": "Perfekt für Dating-App-Werbung · Dialoge wie echte Chats",
        },
    ]


def feature_chips_html() -> str:
    from jam.dialog_shop import DIALOG_PASSES

    week = DIALOG_PASSES["dialog_week"]["price_eur"]
    chips = [
        "🎬 bis 2 Min.",
        "👄 Lip-Sync",
        "📱 9:16 · 4K",
        "🔊 KI-Stimmen",
        "🏠 WLAN-Shop",
        f"ab {week:.2f} €/Wo",
    ]
    return "".join(f'<span class="feat-chip">{c}</span>' for c in chips)


def features_card_html() -> str:
    items = "".join(
        f"""<li class="feat-item">
  <span class="feat-icon">{f["icon"]}</span>
  <div><strong>{f["title"]}</strong><br><span class="feat-desc">{f["text"]}</span></div>
</li>"""
        for f in program_features()
    )
    return f"""<div class="card sidebar-card features-card">
  <label>✨ Was {PRODUCT_BRAND} kann</label>
  <ul class="feat-list">{items}</ul>
</div>"""


def jami_dating_sidebar_html(*, utm_source: str = "dialog_studio") -> str:
    banner = jami_promo_banner_html(
        variant="compact",
        utm_source=utm_source,
        utm_medium="sidebar",
        animated=True,
    )
    return f"""<div class="card sidebar-card jami-ad-card">
  <label>Dating-App</label>
  {banner}
  <p class="hint jami-ad-hint"><a href="{jami_signup_url(utm_source=utm_source, utm_medium='sidebar')}" target="_blank" rel="noopener sponsored">jami-dating.de</a> · 100 Coins gratis · echte Singles</p>
</div>"""


def studio_marketing_css() -> str:
    return (
        jami_promo_banner_css(animated=True, variant="compact")
        + """
.layout{display:grid;grid-template-columns:1fr min(300px,28vw);gap:1.25rem;align-items:start}
@media(max-width:1024px){.layout{grid-template-columns:1fr}}
.sidebar{display:flex;flex-direction:column;gap:1.25rem;position:sticky;top:1rem}
@media(max-width:1024px){.sidebar{position:static}}
.sidebar-card{padding:1rem}
.sidebar-card>label{margin-bottom:.65rem}
.feat-chips{display:flex;flex-wrap:wrap;gap:.45rem;margin:.75rem 0 1.25rem}
.feat-chip{font-size:.75rem;padding:.3rem .65rem;border-radius:999px;background:rgba(168,85,247,.15);border:1px solid rgba(168,85,247,.35);color:#e9d5ff}
.feat-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:.85rem}
.feat-item{display:flex;gap:.65rem;align-items:flex-start;font-size:.82rem;line-height:1.45}
.feat-icon{font-size:1.15rem;line-height:1;flex-shrink:0}
.feat-desc{color:var(--muted);font-size:.78rem}
.jami-ad-card .jami-ad-embed{margin-top:.25rem}
.jami-ad-hint{margin-top:.65rem;margin-bottom:0;text-align:center}
"""
    )


def studio_marketing_script() -> str:
    return jami_promo_banner_script(animated=True)


def social_post_templates(*, lan_url: str = "") -> dict[str, str]:
    from jam.dialog_shop import DIALOG_PASSES

    week = DIALOG_PASSES["dialog_week"]["price_eur"]
    jami = jami_signup_url(utm_source="social", utm_medium="post")
    features = " · ".join(f["title"] for f in program_features()[:4])
    return {
        "tiktok": (
            f"🎬 VidPuls macht Dating-Promos in 2 Min!\n"
            f"Zeitpass ab {week:.2f} €/Woche · unbegrenzt\n"
            f"3D-Figuren · Lip-Sync · TikTok 9:16\n"
            f"{lan_url or 'Im WLAN testen'}\n\n"
            f"💜 Singles? → {jami}\n\n"
            f"#dating #tiktok #ki #videomarketing #single #jami"
        ),
        "instagram": (
            f"Promo-Videos bis 2 Minuten – ohne teures Studio.\n\n"
            f"✓ 3D-Dialoge Sarah & Laura\n"
            f"✓ Echte Lippenbewegung (Lip-Sync)\n"
            f"✓ 1080p & 4K · 9:16\n"
            f"✓ Zeitpass: 1 Wo · 1 Mo · 6 Mo · 1 Jahr\n"
            f"✓ Ab {week:.2f} € · unbegrenzt im Zeitraum\n\n"
            f"Perfekt für Dating-Apps & Social Ads.\n\n"
            f"💜 Jami-Dating testen: {jami}\n"
            f"#vidpuls #dating #contentcreator #reels"
        ),
        "kurz": (
            f"{PRODUCT_BRAND}: 3D Dating-Videos · Zeitpass ab {week:.2f} €/Wo. "
            f"Jami-Dating: {JAMI_SITE_URL}"
        ),
    }


def export_program_werbung(out_dir: Path, *, lan_url: str = "") -> list[Path]:
    """Werbung: Funktionen + Social-Posts + HTML-Sidebar-Snippet."""
    out_dir.mkdir(parents=True, exist_ok=True)
    paths: list[Path] = []

    lines = [
        f"{PRODUCT_BRAND} – Was das Programm kann",
        "=" * 48,
        "",
        "HIGHLIGHTS:",
    ]
    for f in program_features():
        lines.append(f"  {f['icon']} {f['title']}")
        lines.append(f"     {f['text']}")
        lines.append("")
    from jam.dialog_shop import DIALOG_PASSES

    lines.extend(["PREISE (Zeitpässe – unbegrenzt Videos):"])
    for p in DIALOG_PASSES.values():
        lines.append(f"  · {p['name']}: {p['price_eur']:.2f} €")
    lines.extend(
        [
            "",
            f"Jami-Dating (Cross-Promo): {JAMI_SITE_URL}",
            f"  Anmelden: {jami_signup_url(utm_source='werbung', utm_medium='txt')}",
            "",
        ]
    )
    if lan_url:
        lines.append(f"WLAN-Shop für Freunde: {lan_url}")
        lines.append("")

    posts = social_post_templates(lan_url=lan_url)
    lines.append("SOCIAL POST – TikTok:")
    lines.append(posts["tiktok"])
    lines.append("")
    lines.append("SOCIAL POST – Instagram:")
    lines.append(posts["instagram"])

    txt = out_dir / "WERBUNG-PROGRAMM-FUNKTIONEN.txt"
    txt.write_text("\n".join(lines) + "\n", encoding="utf-8")
    paths.append(txt)

    (out_dir / "social-posts.json").write_text(
        json.dumps(posts, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    paths.append(out_dir / "social-posts.json")

    sidebar_html = f"""<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>{PRODUCT_BRAND} Sidebar-Werbung</title>
<style>
body{{font-family:Segoe UI,sans-serif;background:#07050f;color:#f1ecff;padding:1rem;max-width:320px;margin:0 auto}}
{studio_marketing_css()}
</style>
</head>
<body>
<div class="sidebar">
{features_card_html()}
{jami_dating_sidebar_html(utm_source="embed")}
</div>
{studio_marketing_script()}
</body>
</html>"""
    side = out_dir / "werbung-sidebar.html"
    side.write_text(sidebar_html, encoding="utf-8")
    paths.append(side)

    dating_only = out_dir / "werbung-jami-dating.html"
    dating_only.write_text(
        f"""<!DOCTYPE html>
<html lang="de"><head><meta charset="utf-8"/>
<style>{jami_promo_banner_css(animated=True, variant="compact")}</style></head>
<body style="margin:0;padding:1rem;background:#07050f">
{jami_promo_banner_html(variant="compact", utm_source="werbung", utm_medium="html")}
{jami_promo_banner_script(animated=True)}
</body></html>""",
        encoding="utf-8",
    )
    paths.append(dating_only)

    return paths
