"""VidPuls-Werbebanner für Jami-Dating (Cross-Promo, Sidebar)."""

from __future__ import annotations

import html
import urllib.parse

from jam.jampulse_brand import MINUTE_OFFER, PRODUCT_BRAND, PRODUCT_SITE_URL

VIDPULS_SITE_URL = PRODUCT_SITE_URL.rstrip("/")


def vidpuls_cta_url(
    *,
    utm_source: str = "jami_dating",
    utm_medium: str = "sidebar",
    utm_campaign: str = "crosspromo",
) -> str:
    q = urllib.parse.urlencode(
        {
            "utm_source": utm_source,
            "utm_medium": utm_medium,
            "utm_campaign": utm_campaign,
        }
    )
    return f"{VIDPULS_SITE_URL}/?{q}"


def vidpuls_ad_embed_css(*, compact: bool = False) -> str:
    flow_size = "140px" if compact else "min(100%, 260px)"
    flow_margin = "0.35rem auto 0.5rem" if compact else "0.5rem auto 0.75rem"
    center_size = "52px" if compact else "72px"
    head_size = "0.82rem" if compact else "clamp(1rem, 3vw, 1.25rem)"
    return f"""
.vp-ad-embed {{
  display: block;
  text-decoration: none;
  color: #fff;
  border-radius: 16px;
  overflow: hidden;
  position: relative;
  border: 1px solid rgba(168, 85, 247, 0.45);
  background:
    radial-gradient(ellipse 100% 50% at 50% 0%, rgba(120,60,200,0.45), transparent 55%),
    radial-gradient(ellipse 80% 40% at 20% 80%, rgba(236,72,153,0.2), transparent 50%),
    linear-gradient(180deg, #1a0a28 0%, #0c0612 100%);
  box-shadow: 0 12px 40px rgba(0,0,0,0.35);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}}
.vp-ad-embed:hover {{
  transform: translateY(-2px);
  box-shadow: 0 16px 48px rgba(168,85,247,0.28);
}}
.vp-ad-embed-inner {{
  padding: 0.85rem 0.9rem 1rem;
  text-align: center;
  position: relative;
  z-index: 1;
}}
.vp-ad-embed--wide .vp-ad-embed-inner {{
  display: grid;
  grid-template-columns: 1fr min(260px, 38%);
  gap: 0.75rem 1rem;
  align-items: center;
  text-align: left;
  padding: 1rem 1.15rem;
}}
.vp-ad-embed-head h3 {{
  margin: 0 0 0.35rem;
  font-size: {head_size};
  line-height: 1.2;
  font-weight: 800;
}}
.vp-ad-embed-head h3 em {{ font-style: normal; color: #ffd54f; }}
.vp-ad-embed-head p {{
  margin: 0 0 0.5rem;
  font-size: 0.78rem;
  color: rgba(255,255,255,0.82);
  line-height: 1.4;
}}
.vp-ad-embed-badge {{
  display: inline-block;
  font-size: 0.65rem;
  font-weight: 700;
  letter-spacing: 0.04em;
  text-transform: uppercase;
  color: #e9d5ff;
  margin-bottom: 0.35rem;
}}
.vp-ad-flow {{
  position: relative;
  width: {flow_size};
  aspect-ratio: 1;
  margin: {flow_margin};
}}
.vp-ad-center {{
  position: absolute;
  left: 50%; top: 50%;
  transform: translate(-50%, -50%);
  width: {center_size}; height: {center_size};
  border-radius: 22%;
  display: grid;
  place-items: center;
  font-size: calc({center_size} * 0.45);
  background: linear-gradient(135deg, #a855f7, #ec4899);
  box-shadow: 0 0 0 4px rgba(168,85,247,0.35), 0 0 28px rgba(168,85,247,0.45);
  animation: vpAdCenterPulse 2.5s ease-in-out infinite;
  z-index: 2;
}}
@keyframes vpAdCenterPulse {{
  0%, 100% {{ transform: translate(-50%, -50%) scale(1); }}
  50% {{ transform: translate(-50%, -50%) scale(1.05); }}
}}
.vp-ad-ring {{
  position: absolute; inset: 0;
  border: 2px dashed rgba(168,85,247,0.3);
  border-radius: 50%;
  animation: vpAdRingSpin 24s linear infinite;
}}
@keyframes vpAdRingSpin {{ to {{ transform: rotate(360deg); }} }}
.vp-ad-step {{
  position: absolute;
  width: 44%;
  padding: 0.3rem 0.25rem;
  background: rgba(255,255,255,0.08);
  border: 1px solid rgba(255,255,255,0.12);
  border-radius: 10px;
  font-size: 0.58rem;
  line-height: 1.2;
  font-weight: 600;
  opacity: 0.45;
  transition: opacity 0.4s, transform 0.4s, box-shadow 0.4s;
  text-align: center;
}}
.vp-ad-step .ico {{ font-size: 0.95rem; display: block; margin-bottom: 0.1rem; }}
.vp-ad-step.is-on {{
  opacity: 1;
  box-shadow: 0 0 16px rgba(168,85,247,0.35);
  border-color: rgba(168,85,247,0.45);
  background: rgba(168,85,247,0.12);
}}
.vp-ad-step:nth-child(2) {{ top: 2%; left: 50%; transform: translateX(-50%); }}
.vp-ad-step:nth-child(3) {{ top: 50%; right: 0; transform: translateY(-50%); }}
.vp-ad-step:nth-child(4) {{ bottom: 2%; left: 50%; transform: translateX(-50%); }}
.vp-ad-step:nth-child(5) {{ top: 50%; left: 0; transform: translateY(-50%); }}
.vp-ad-stat {{
  display: inline-block;
  padding: 0.3rem 0.65rem;
  border-radius: 999px;
  background: linear-gradient(135deg, rgba(168,85,247,0.25), rgba(236,72,153,0.2));
  border: 1px solid rgba(168,85,247,0.4);
  font-size: 0.68rem;
  font-weight: 700;
  margin-bottom: 0.55rem;
}}
.vp-ad-cta {{
  display: inline-block;
  width: 100%;
  padding: 0.55rem 0.85rem;
  border-radius: 12px;
  background: linear-gradient(135deg, #a855f7, #ec4899);
  color: #fff;
  font-weight: 800;
  font-size: 0.82rem;
  text-align: center;
}}
.vp-ad-foot {{
  margin-top: 0.45rem;
  font-size: 0.6rem;
  color: rgba(255,255,255,0.38);
  text-align: center;
}}
.vp-ad-sparks {{
  position: absolute; inset: 0; pointer-events: none; overflow: hidden; border-radius: 16px; z-index: 0;
}}
.vp-ad-spark {{
  position: absolute; font-size: 0.85rem; opacity: 0;
  animation: vpAdSparkFloat var(--d, 14s) linear infinite;
  animation-delay: var(--delay, 0s);
  left: var(--x, 50%);
  bottom: -1rem;
}}
@keyframes vpAdSparkFloat {{
  0% {{ transform: translateY(0); opacity: 0; }}
  10% {{ opacity: 0.55; }}
  90% {{ opacity: 0.35; }}
  100% {{ transform: translateY(-120px); opacity: 0; }}
}}
@media (prefers-reduced-motion: reduce) {{
  .vp-ad-embed *, .vp-ad-embed *::before, .vp-ad-embed *::after {{ animation: none !important; }}
  .vp-ad-step {{ opacity: 1; }}
}}
"""


def vidpuls_ad_embed_html(
    *,
    cta_url: str,
    variant: str = "compact",
    embed_id: str = "vpAd",
) -> str:
    href = html.escape(cta_url)
    mod = "vp-ad-embed--wide" if variant == "wide" else "vp-ad-embed--compact"
    uid = html.escape(embed_id)
    max_sec = int(MINUTE_OFFER.get("duration_max_sec") or 120)
    return f"""<a class="vp-ad-embed {mod}" href="{href}" target="_blank" rel="noopener sponsored" id="{uid}">
  <div class="vp-ad-sparks" aria-hidden="true">
    <span class="vp-ad-spark" style="--x:15%;--d:12s;--delay:0s">🎬</span>
    <span class="vp-ad-spark" style="--x:75%;--d:15s;--delay:2s">✨</span>
    <span class="vp-ad-spark" style="--x:45%;--d:13s;--delay:1s">📱</span>
  </div>
  <div class="vp-ad-embed-inner">
    <span class="vp-ad-embed-badge">🎬 {html.escape(PRODUCT_BRAND)} · Partner-Tipp</span>
    <header class="vp-ad-embed-head">
      <h3>Dating-Videos bis <em>2 Minuten</em> – KI &amp; 3D</h3>
      <p>Dialog · Lip-Sync · TikTok 9:16 · ab {_week_price_label()}/Woche</p>
    </header>
    <div class="vp-ad-flow-wrap">
      <div class="vp-ad-flow" data-vp-ad-flow="{uid}">
        <div class="vp-ad-ring" aria-hidden="true"></div>
        <div class="vp-ad-step"><span class="ico">✍️</span>Text</div>
        <div class="vp-ad-step"><span class="ico">🔊</span>KI-Stimmen</div>
        <div class="vp-ad-step"><span class="ico">👄</span>Lip-Sync</div>
        <div class="vp-ad-step"><span class="ico">📱</span>MP4 fertig</div>
        <div class="vp-ad-center" aria-hidden="true">🎬</div>
      </div>
    </div>
    <p class="vp-ad-stat">⏱ bis {max_sec} Sek. · 1080p &amp; 4K · PayPal</p>
    <span class="vp-ad-cta">VidPuls testen →</span>
    <p class="vp-ad-foot">{html.escape(VIDPULS_SITE_URL.replace('https://', ''))}</p>
  </div>
</a>"""


def vidpuls_ad_embed_script() -> str:
    return """
(function(){
  document.querySelectorAll('[data-vp-ad-flow]').forEach(function(flow){
    var steps = flow.querySelectorAll('.vp-ad-step');
    if (!steps.length) return;
    var n = 0;
    function tick(){
      for (var i = 0; i < steps.length; i++) steps[i].classList.remove('is-on');
      steps[n].classList.add('is-on');
      n = (n + 1) % steps.length;
    }
    tick();
    setInterval(tick, 1800);
  });
})();
"""


def site_promo_layout_css() -> str:
    return """
.landing-with-sidebar {
  display: grid;
  grid-template-columns: 1fr min(280px, 26vw);
  gap: 1.25rem 1.5rem;
  max-width: 1380px;
  margin: 0 auto;
  padding: 0 clamp(1rem, 4vw, 2rem);
  align-items: start;
}
.landing-sidebar {
  position: sticky;
  top: 1rem;
  z-index: 3;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.landing-sidebar-card {
  background: rgba(18, 16, 31, 0.92);
  border: 1px solid rgba(168, 85, 247, 0.28);
  border-radius: 16px;
  padding: 0.85rem;
}
.landing-sidebar-card label {
  display: block;
  font-size: 0.72rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  color: var(--muted);
  margin-bottom: 0.55rem;
}
.landing-sidebar-feats {
  list-style: none;
  margin: 0;
  padding: 0;
  font-size: 0.78rem;
  line-height: 1.45;
  color: var(--muted);
}
.landing-sidebar-feats li { margin: 0.35rem 0; padding-left: 0; }
.landing-sidebar-feats strong { color: var(--text); }
.vidpuls-promo-section { margin: 2rem 0 0; }
@media (max-width: 1024px) {
  .landing-with-sidebar { grid-template-columns: 1fr; }
  .landing-sidebar { position: static; order: 10; max-width: 420px; margin: 0 auto; }
}
.app-vidpuls-sidebar-in {
  display: none;
}
@media (min-width: 1100px) {
  #appShell:not(.hidden) .app-vidpuls-sidebar-in {
    display: block;
    position: fixed;
    top: 4.5rem;
    right: max(0.75rem, calc((100vw - 520px) / 2 - 290px));
    width: 260px;
    z-index: 90;
  }
}
"""


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

        return f"{DIALOG_PASSES['dialog_week']['price_eur']:.2f} €"
    except ImportError:
        return "6,99 €"


def _feature_list_html() -> str:
    max_sec = int(MINUTE_OFFER.get("duration_max_sec") or 120)
    items = [
        f"<li><strong>🎬 bis {max_sec} Sek.</strong> Promo &amp; Dialog</li>",
        "<li><strong>👄 3D Lip-Sync</strong> Sarah &amp; Laura</li>",
        "<li><strong>📱 9:16</strong> TikTok &amp; Reels</li>",
        f"<li><strong>💳 ab {_week_price_label()}</strong> 1 Wo · 1 Mo · 6 Mo · 1 Jahr</li>",
    ]
    return f'<ul class="landing-sidebar-feats">{"".join(items)}</ul>'


def landing_sidebar_html(*, utm_source: str = "jami_landing") -> str:
    banner = vidpuls_ad_embed_html(
        cta_url=vidpuls_cta_url(utm_source=utm_source, utm_medium="sidebar"),
        variant="compact",
        embed_id="vpAdLanding",
    )
    return f"""<aside class="landing-sidebar" aria-label="VidPuls Partner">
  <div class="landing-sidebar-card">
    <label>KI-Video für Dating</label>
    {banner}
  </div>
  <div class="landing-sidebar-card">
    <label>Was {html.escape(PRODUCT_BRAND)} kann</label>
    {_feature_list_html()}
  </div>
</aside>"""


def landing_section_html(*, utm_source: str = "jami_landing") -> str:
    """Breite Promo-Zeile in der Landing (mobil sichtbar)."""
    banner = vidpuls_ad_embed_html(
        cta_url=vidpuls_cta_url(utm_source=utm_source, utm_medium="section"),
        variant="wide",
        embed_id="vpAdSection",
    )
    return f"""<section class="vidpuls-promo-section landing-section" id="vidpuls-promo" aria-label="VidPuls">
  {banner}
</section>"""


def app_sidebar_html(*, utm_source: str = "jami_app") -> str:
    return vidpuls_ad_embed_html(
        cta_url=vidpuls_cta_url(utm_source=utm_source, utm_medium="app_sidebar"),
        variant="compact",
        embed_id="vpAdApp",
    )


def site_promo_bundle() -> dict[str, str]:
    """CSS + HTML-Fragmente + Script für Jami-Dating Build."""
    return {
        "css": vidpuls_ad_embed_css(compact=True) + site_promo_layout_css(),
        "script": vidpuls_ad_embed_script(),
        "landing_sidebar": landing_sidebar_html(),
        "landing_section": landing_section_html(),
        "app_sidebar": f'<aside class="app-vidpuls-sidebar-in" aria-label="VidPuls">{app_sidebar_html()}</aside>',
    }
