// ─── Social Ads — faithful native ad previews per platform & placement ───
const ADS = window.ADS;
const adBrand = (b) => ADS.meta.brands[b] || { accent: "#888", page: b, handle: "@" + b.toLowerCase(), domain: b.toLowerCase() + ".com", products: [] };
const ST = { active: "Active", ready: "Ready to launch", review: "In review", draft: "Draft" };
const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const fmtDate = (s) => { if (!s) return ""; const [, m, d] = s.split("-"); return MON[+m - 1] + " " + (+d); };
const platTint = (p) => ({ tiktok: "#fe2c55", youtube: "#ff0000", google: "#1a73e8", meta: "#0866ff" }[p] || "#0866ff");
const PLAT_DOT = { amazon: "#ff9900", meta: "#0866ff", tiktok: "#111", youtube: "#ff0000", google: "#4285f4" };

// Brand avatar — the official logo on a white circle (falls back to a letter mark).
function Avatar({ a, cls, children }) {
  const br = adBrand(a.brand);
  const cover = br.logoFit === "cover"; // full-bleed wordmark logos (e.g. Claritin) fill the circle on the brand color
  return (
    <span className={cls} style={{ background: br.logo ? (cover ? br.accent : "#fff") : br.accent }}>
      {br.logo ? <img className={"brand-logo" + (cover ? " cover" : "")} src={br.logo} alt={br.page}/> : a.brand[0]}
      {children}
    </span>
  );
}

// Shared creative media — playable video, frozen frame (still), or static image.
function AdMedia({ a, still }) {
  const ref = useRef(null);
  const [on, setOn] = useState(false);
  const play = (e) => { e.stopPropagation(); const v = ref.current; if (v) v.play().catch(() => {}); };
  if (a.format === "image") return <img className="adm-img" src={a.url} alt={a.concept} loading="lazy"/>;
  if (still) return <video className="adm-still" src={a.url + "#t=2"} preload="metadata" muted playsInline/>;
  return (
    <>
      <video ref={ref} className="adm-vid" src={a.url + "#t=0.1"} poster={a.poster || undefined}
        preload="metadata" playsInline loop controls={on}
        onPlay={() => setOn(true)} onPause={() => setOn(false)}/>
      {!on && <button type="button" className="adm-play" onClick={play} aria-label="Play"><Ico d="play" size={18} fill/></button>}
      {a.duration && !on && <span className="adm-dur">{a.duration}s</span>}
    </>
  );
}

// ── Meta — Facebook / Instagram feed ──
function MetaAd({ a }) {
  const br = adBrand(a.brand);
  return (
    <div className="fb-ad">
      <div className="fb-hd">
        <Avatar a={a} cls="fb-av"/>
        <span className="fb-nm">{br.page}<small>Sponsored · 🌐</small></span>
        <span className="fb-more">···</span>
      </div>
      <div className="fb-txt">{a.primaryText}</div>
      <div className="adm-stage fb-media"><AdMedia a={a}/></div>
      <div className="fb-link">
        <div className="fb-lk-t"><div className="dom">{br.domain}</div><div className="hl">{a.headline}</div></div>
        <span className="fb-cta">{a.cta}</span>
      </div>
      <div className="fb-react"><span>👍 Like</span><span>💬 Comment</span><span>↗ Share</span></div>
    </div>
  );
}

// ── YouTube — in-stream ──
function YouTubeAd({ a }) {
  const br = adBrand(a.brand);
  return (
    <div className="yt-ad">
      <div className="adm-stage yt-media">
        <AdMedia a={a}/>
        <span className="yt-badge">Ad</span>
        <span className="yt-skip">Skip ⏭</span>
      </div>
      <div className="yt-info">
        <Avatar a={a} cls="yt-ch"/>
        <div className="yt-meta"><div className="t">{a.headline}</div><div className="c">{br.page} · Sponsored</div></div>
        <span className="yt-visit">{a.cta}</span>
      </div>
    </div>
  );
}

// ── Google — Demand Gen / Display native ──
function GoogleAd({ a }) {
  const br = adBrand(a.brand);
  return (
    <div className="gg-ad">
      <div className="adm-stage gg-media"><AdMedia a={a}/></div>
      <div className="gg-body">
        <div className="gg-lbl"><span className="gg-adtag">Ad</span> · {br.domain}</div>
        <div className="gg-hl">{a.headline}</div>
        <div className="gg-desc">{a.description || a.primaryText}</div>
        <div className="gg-foot">
          <Avatar a={a} cls="gg-logo"/>
          <span className="gg-nm">{br.page}</span>
          <span className="gg-cta">{a.cta}</span>
        </div>
      </div>
    </div>
  );
}

// ── Vertical — platform-specific: TikTok For You · IG/FB Reels · YouTube Shorts · Google vertical ──
function VerticalAd({ a, plat }) {
  const br = adBrand(a.brand);
  const tint = platTint(plat);
  const logoCls = "brand-logo" + (br.logoFit === "cover" ? " cover" : "");
  return (
    <div className={`vt-ad vt-${plat}`}>
      <div className="adm-stage vt-media"><AdMedia a={a}/></div>
      <span className="vt-spon">Sponsored</span>
      {plat === "meta" && <span className="vt-badge">Reels</span>}
      {plat === "youtube" && <span className="vt-badge yt">Shorts</span>}
      <div className="vt-rail">
        {plat === "tiktok" && <>
          <Avatar a={a} cls="vt-prof"><i>+</i></Avatar>
          <span className="vt-ic">❤<small>12.4k</small></span>
          <span className="vt-ic">💬<small>318</small></span>
          <span className="vt-ic">↗<small>Share</small></span>
          <span className="vt-disc">♪</span>
        </>}
        {plat === "meta" && <>
          <span className="vt-ic">❤<small>12.4k</small></span>
          <span className="vt-ic">💬<small>318</small></span>
          <span className="vt-ic">➤<small>Share</small></span>
          <span className="vt-ic">⋯</span>
          <span className="vt-art"><img className={logoCls} src={br.logo} alt=""/></span>
        </>}
        {plat === "youtube" && <>
          <span className="vt-ic">👍<small>12k</small></span>
          <span className="vt-ic">👎<small>Dislike</small></span>
          <span className="vt-ic">💬<small>318</small></span>
          <span className="vt-ic">↪<small>Share</small></span>
          <span className="vt-ic">🔁<small>Remix</small></span>
          <span className="vt-art"><img className={logoCls} src={br.logo} alt=""/></span>
        </>}
        {plat === "google" && <>
          <span className="vt-ic">❤</span>
          <span className="vt-ic">↗</span>
        </>}
      </div>
      <div className="vt-cap">
        {plat === "youtube" ? (
          <div className="vt-chrow"><Avatar a={a} cls="vt-cav"/><span className="vt-chn">{br.handle}</span><span className="vt-sub">Subscribe</span></div>
        ) : plat === "tiktok" ? (
          <div className="vt-h">{br.handle}</div>
        ) : (
          <div className="vt-chrow"><Avatar a={a} cls="vt-cav"/><span className="vt-chn">{br.handle.replace("@", "")} <em>· Sponsored</em></span></div>
        )}
        <div className="vt-c">{a.primaryText}</div>
        {plat !== "youtube" && <div className="vt-mus">♪ original audio — {br.page}</div>}
        <div className="vt-cta" style={{ background: tint }}>{plat === "youtube" ? "Visit site" : a.cta} ›</div>
      </div>
    </div>
  );
}

// ── Image — static creative (frozen frame) in a feed-style unit ──
function ImageAd({ a, plat }) {
  const br = adBrand(a.brand);
  return (
    <div className="im-ad">
      <div className="im-hd"><Avatar a={a} cls="im-av"/><span className="im-nm">{br.page}<small>Sponsored</small></span></div>
      <div className="adm-stage im-media"><AdMedia a={a} still/></div>
      <div className="im-foot"><span className="im-hl">{a.headline}</span><span className="im-cta" style={{ background: platTint(plat) }}>{a.cta}</span></div>
    </div>
  );
}

// Amazon star bar (fractional orange fill).
function Stars({ r }) { return <span className="amz-stars"><span className="amz-fill" style={{ width: (r / 5 * 100) + "%" }}></span></span>; }

// ── Amazon — Sponsored Brands (logo header + brand video + product carousel) ──
function SponsoredBrandsAd({ a }) {
  const br = adBrand(a.brand);
  const prods = (br.products || []).slice(0, 3);
  const az = a.amazon || {};
  const sbLogo = br.sbLogo || br.logo; // brands can carry a dedicated horizontal Sponsored-Brands wordmark
  return (
    <div className="sb-ad">
      <div className="sb-hd">
        <span className="sb-logo">{sbLogo ? <img className="brand-logo" src={sbLogo} alt={br.page}/> : <span className="sb-logo-txt" style={{ color: br.accent }}>{br.page}</span>}</span>
        <div className="sb-hdt"><div className="sb-hl">{az.sbHeadline || a.headline}</div><a className="sb-shop">Shop {br.page}® ›</a></div>
      </div>
      <div className="sb-body">
        <div className="adm-stage sb-video"><AdMedia a={a}/><span className="sb-new">New &amp; Notable</span></div>
        <div className="sb-prods">
          {prods.map((p, i) => (
            <div key={i} className="sb-pcard">
              <div className="sb-pimg"><img src={p.img} alt=""/></div>
              <div className="sb-pt">{p.title}</div>
              <div className="sb-prate"><b>{p.rating}</b> <Stars r={p.rating}/> <span className="sb-prev">{p.reviews}</span></div>
            </div>
          ))}
        </div>
      </div>
      <div className="sb-spon">Sponsored ⓘ</div>
    </div>
  );
}

// ── Amazon — Sponsored Brands Video (in-search: video + product + details) ──
function SponsoredBrandsVideoAd({ a }) {
  const br = adBrand(a.brand);
  const az = a.amazon || {}; const prod = (br.products || [])[0];
  return (
    <div className="sbv-ad">
      <div className="adm-stage sbv-video"><AdMedia a={a}/></div>
      {prod && <div className="sbv-pimg"><img src={prod.img} alt=""/></div>}
      <div className="sbv-info">
        <div className="sbv-spon">Sponsored ⓘ</div>
        <div className="sbv-t">{az.title || a.product}</div>
        <div className="sbv-rate"><b>{az.rating}</b> <Stars r={az.rating}/> <span className="sbv-rev">({az.reviews})</span></div>
        <div className="sbv-price"><sup>$</sup>{az.price}<sup>{az.cents}</sup> <span className="sbv-pc">(${az.price}.{az.cents}/count)</span></div>
        <div className="sbv-deliv">FREE delivery <b>{az.delivery}</b></div>
      </div>
    </div>
  );
}

// ── Amazon — Sponsored Display (creative + LEARN MORE + product card w/ list price) ──
function SponsoredDisplayAd({ a }) {
  const br = adBrand(a.brand);
  const az = a.amazon || {}; const prod = (br.products || [])[0];
  return (
    <div className="sd-ad">
      <div className="adm-stage sd-creative"><AdMedia a={a}/></div>
      <div className="sd-prod">
        {prod && <img className="sd-pimg" src={prod.img} alt=""/>}
        <div className="sd-pinfo">
          <div className="sd-t">{az.title || a.product}</div>
          <div className="sd-rate"><b>{az.rating}</b> <Stars r={az.rating}/> <span>{az.reviews}</span></div>
          <div className="sd-price">${az.price}.{az.cents} <span className="sd-list">List: ${az.list}</span></div>
        </div>
      </div>
    </div>
  );
}

// Resolve the creative shown on OUR side for a placement — some placements showcase a different hero:
//  • feed (Meta / YouTube / Google) → the no-captions cut
//  • SBV (Sponsored Brands Video) → the NOTTS Extra Strength pain CGI pill spot (vs Tylenol's)
function effectiveCreative(a, pl) {
  if (pl.kind === "feed" && a.feedUrl) return { ...a, url: a.feedUrl };
  if (pl.kind === "sbv" && a.sbv) return { ...a, ...a.sbv };
  return a;
}

// Render an (already-resolved) creative in a specific platform placement.
function Placement({ a, plat, pl }) {
  if (pl.kind === "sb") return <SponsoredBrandsAd a={a}/>;
  if (pl.kind === "sbv") return <SponsoredBrandsVideoAd a={a}/>;
  if (pl.kind === "sd") return <SponsoredDisplayAd a={a}/>;
  if (pl.kind === "vertical") return <VerticalAd a={a} plat={plat}/>;
  if (pl.kind === "image") return <ImageAd a={a} plat={plat}/>;
  if (plat === "youtube") return <YouTubeAd a={a}/>;
  if (plat === "google") return <GoogleAd a={a}/>;
  return <MetaAd a={a}/>;
}

// Build a competitor (Tylenol) creative for a given platform/placement, using the right media cut.
function competitorCreative(plat, kind) {
  const c = ADS.meta.competitor;
  // Vertical placements (Reels / For You / Shorts / vertical) compare allergy-vs-allergy against Claritin's UGC reel.
  if (kind === "vertical") {
    const cl = ADS.meta.claritin;
    return { brand: cl.brand, product: cl.headline, format: "video", aspect: "9:16", duration: 8, url: cl.media.vertical, poster: null,
      primaryText: cl.primaryText, headline: cl.headline, description: cl.description, cta: cl.cta, amazon: c.amazon, price: 0, bill: "ad" };
  }
  // Sponsored Brands carousel → Claritin's brand video + its 3 allergy products (allergy-vs-allergy).
  if (kind === "sb") {
    const cl = ADS.meta.claritin;
    return { brand: cl.brand, format: "video", aspect: "16:9", duration: null, url: cl.media.sb, poster: null,
      headline: cl.sbHeadline, cta: cl.cta, amazon: { sbHeadline: cl.sbHeadline }, price: 0, bill: "ad" };
  }
  let url = c.media.horizontal, format = "video";
  if (kind === "feed") url = c.media.dad; // Meta Feed / YouTube In-stream / Google Demand Gen → Tylenol "Dad" commercial
  else if (kind === "sbv") url = c.media.cgi2; // Sponsored Brands Video → Tylenol's second CGI pill spot
  else if (kind === "image") { url = c.media.image; format = "image"; } // Meta/TikTok Image, YouTube/Google Display → Tylenol static CTA display ad
  return { brand: c.brand, product: c.amazon.title, format, aspect: "16:9", duration: null, url, poster: null,
    primaryText: c.primaryText, headline: c.headline, description: c.description, cta: c.cta, amazon: c.amazon, price: 0, bill: "ad" };
}

// Creative-level deliverable strip — status / turnaround / versions / live-since / price. Shown ONCE per creative (price is not per-placement).
function CreativeMeta({ a, plat }) {
  const live = (a.liveOn || []).includes(plat);
  const st = live ? "active" : (a.status || "active");
  return (
    <div className="ad-meta">
      <span className={`ad-st ${st}`}><span className="d"></span>{ST[st]}</span>
      {a.producedIn && <span className="ad-24"><Ico d="bolt" size={11}/>{a.producedIn}</span>}
      {a.variants > 1 && <span className="ad-ver">{a.variants} versions</span>}
      {live && a.startedRunning && <span className="ad-since">Live since {fmtDate(a.startedRunning)}</span>}
      <span className="bill paid ad-price">{money(a.price)}</span>
    </div>
  );
}

// One placement rendered in its native chrome, with the Tylenol competitor side-by-side ("⇄ vs Tylenol" toggles it; on by default).
function AdCard({ a, plat, pl }) {
  const [cmp, setCmp] = useState(true);
  const ours = effectiveCreative(a, pl);
  const comp = competitorCreative(plat, pl.kind);
  return (
    <article className={`adcard plat-${plat} kind-${pl.kind} ${cmp ? "comparing" : ""}`}>
      <div className="ad-plrow">
        <span className="ad-pln">{pl.n}</span>
        <button type="button" className="ad-cmp" onClick={() => setCmp((v) => !v)}>{cmp ? "✕ Hide compare" : "⇄ vs " + comp.brand}</button>
      </div>
      <div className="ad-pair">
        <div className="ad-side">
          <div className="ad-side-lbl" style={{ color: adBrand(ours.brand).accent }}>{ours.brand} — ours</div>
          <div className="ad-preview"><Placement a={ours} plat={plat} pl={pl}/></div>
        </div>
        {cmp && (
          <div className="ad-side ad-comp">
            <div className="ad-side-lbl comp" style={{ color: adBrand(comp.brand).accent }}>{comp.brand} — competitor</div>
            <div className="ad-preview"><Placement a={comp} plat={plat} pl={pl}/></div>
          </div>
        )}
      </div>
    </article>
  );
}

// A platform's section: each creative shows its deliverable strip once, then EVERY placement as its own competitor-compared sub-card.
function PlatformSection({ plat, creatives }) {
  const meta = ADS.meta.platforms[plat];
  const list = creatives.filter((a) => a.platform.includes(plat));
  if (!list.length) return null;
  const anyLive = list.some((a) => (a.liveOn || []).includes(plat));
  return (
    <section className="plat-sec">
      <div className="plat-head">
        <span className={`plat-badge ${plat}`}></span>
        <span className="plat-n">{meta.label}</span>
        <span className="plat-s">{meta.sub} · {list.length} creative{list.length > 1 ? "s" : ""}</span>
        <span className={`plat-state ${anyLive ? "live" : "ready"}`}>{anyLive ? "● Live" : "○ Ready to launch"}</span>
        <span className="rule"></span>
      </div>
      {list.map((a) => (
        <div key={a.id} className="plat-creative">
          <CreativeMeta a={a} plat={plat}/>
          {meta.placements.map((pl) => <AdCard key={pl.k} a={a} plat={plat} pl={pl}/>)}
        </div>
      ))}
    </section>
  );
}

function SocialAds() {
  const [plat, setPlat] = useState("all");
  const [brand, setBrand] = useState("all");
  const C = ADS.creatives.filter((a) => brand === "all" || a.brand === brand);
  const total = C.reduce((s, a) => s + a.price, 0);
  const liveCount = C.filter((a) => (a.liveOn || []).length).length;
  const allPlats = ["amazon", "meta", "tiktok", "youtube", "google"];
  const shown = allPlats.filter((p) => plat === "all" || plat === p);
  const PLATS = [["all", "All", null], ...allPlats.map((p) => [p, ADS.meta.platforms[p].label, PLAT_DOT[p]])];
  const BRANDS = [["all", "All", null], ["NOTTS", "NOTTS", "#1D428A"], ["AXIV", "AXIV", "#16A34A"]];
  return (
    <main>
      <header className="cat-head">
        <div className="ch-title">
          <div className="eyebrow">Vivunt · Social ad program</div>
          <h1>Social ad creatives — how they appear live</h1>
        </div>
        <div className="kpis">
          <div className="kpi"><span className="kv num">{C.length}</span><span className="kl">Creatives</span></div>
          <div className="kpi"><span className="kv num">{shown.length}</span><span className="kl">Platforms</span></div>
          <div className="kpi"><span className="kv num">{liveCount}</span><span className="kl">Live now</span></div>
          <div className="kpi px-kpi"><span className="kv num">{money(total)}</span><span className="kl">Total</span></div>
        </div>
      </header>
      <div className="toolbar">
        <div className="seg-group">
          <div className="seg">
            {PLATS.map(([v, l, dot]) => (
              <button key={v} aria-pressed={plat === v} onClick={() => setPlat(v)}>
                {dot && <span className="d" style={{ background: dot }}></span>}{l}
              </button>
            ))}
          </div>
          <div className="seg">
            {BRANDS.map(([v, l, dot]) => (
              <button key={v} aria-pressed={brand === v} onClick={() => setBrand(v)}>
                {dot && <span className="d" style={{ background: dot }}></span>}{l}
              </button>
            ))}
          </div>
        </div>
      </div>
      {shown.map((p) => <PlatformSection key={p} plat={p} creatives={C}/>)}
    </main>
  );
}

Object.assign(window, { SocialAds });
