/* global React, window */
// Variants page — selection-first compare (no mode toggle), MetricDelta on cards,
// renders differently for copy_overlay vs image_gen tasks.

const { useState, useMemo, useEffect } = React;

function Variants({ task, ad, onBackToRadar, onPushedToPlatform, allTasksForAd }) {
  const { Icon, Pill, Thumb, VariantPlaceholder, MetricDelta } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const [sort, setSort] = useState("score");
  const [selected, setSelected] = useState(new Set());
  const [starred, setStarred] = useState(new Set([1]));
  const [comparing, setComparing] = useState(false);

  useEffect(() => {
    setSelected(new Set());
    setComparing(false);
  }, [task?.id]);

  if (!ad || !task) return null;
  const rec = ad.recs.find(r => r.id === task.recId) || ad.recs[0];
  const kind = rec.action_kind;

  // build 4 variants
  const variants = window.VARIANT_NAMES.map((v, i) => ({
    ...v, idx: i, id: `${task.id}-v${i}`,
    score: 62 + ((i * 7 + parseInt(task.id.replace(/\D/g, ""), 10) * 3) % 31),
    deltaMul: [1.0, 0.75, 1.15, 0.55][i], // multiplier on rec's primary delta
  }));

  const otherTasks = (allTasksForAd || []).filter(t => t.id !== task.id && t.status === "completed");

  const sorted = [...variants].sort((a, b) => {
    if (sort === "score") return b.score - a.score;
    if (sort === "direction") return a.name.localeCompare(b.name);
    return 0;
  });

  const toggle = (id) => setSelected(s => {
    const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n;
  });
  const toggleStar = (id) => setStarred(s => {
    const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n;
  });

  return (
    <div style={{ padding: "0 24px 80px" }}>
      {/* Header — breadcrumb lives in the top bar now (clickable), so the
          page only carries an eyebrow that names the action_kind to give
          the title block context without duplicating navigation. */}
      <div style={{ padding: "24px 0 12px", display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 32 }}>
        <div>
          <div className="eyebrow">
            {kind === "copy_overlay" ? t("Copy iteration", "文案迭代") : t("Image iteration", "图片迭代")} · {ad.code} · {new Date().toLocaleDateString("en-GB", { day: "2-digit", month: "2-digit" })}
          </div>
          <h1 className="t-display" style={{ fontSize: 44, margin: "6px 0 0" }}>
            <em>{isZh && rec.titleZh ? rec.titleZh : rec.title}.</em>
          </h1>
          <div style={{ marginTop: 8, color: "var(--ink-3)", fontSize: 13, maxWidth: 720, lineHeight: 1.5 }}>
            {isZh && rec.whyZh ? rec.whyZh : rec.why}
          </div>
        </div>
        <div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
          <button
            className="btn sm"
            onClick={() => {
              if (typeof window.__pushToast === "function") {
                window.__pushToast(t(
                  "Queued another batch for this rec — check Tasks.",
                  "已为这条建议再排一批生成 · 查看任务面板。"
                ), "running");
              }
            }}
          >
            <Icon name="refresh" size={12} />{t("Generate more", "再生成几个")}
          </button>
          <button
            className="btn sm ghost"
            onClick={() => {
              if (typeof window.__pushToast === "function") {
                window.__pushToast(t(
                  `Exporting all ${sorted.length} variants to PNG (demo).`,
                  `开始导出全部 ${sorted.length} 个变体为 PNG(演示)。`
                ), "success");
              }
            }}
          >
            <Icon name="download" size={12} />{t("Export all", "全部导出")}
          </button>
        </div>
      </div>

      <div className="hr" />

      {/* Two-column */}
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 24, marginTop: 18 }}>
        {/* Original column */}
        <aside style={{ position: "sticky", top: 0, alignSelf: "start" }}>
          <div className="label">{t("Original ad", "原始广告")}</div>
          <div style={{ marginTop: 6 }}>
            <window.AdCreative ad={ad} w="100%" h={320} big />
          </div>
          <div className="t-h3" style={{ marginTop: 10 }}>{isZh && ad.headlineZh ? ad.headlineZh : ad.headline}</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>
            {ad.code} · {t(`live ${ad.age}`, `已投放 ${ad.age.replace(" weeks", " 周").replace(" week", " 周")}`)}
          </div>

          <div className="hr" style={{ margin: "16px 0" }} />

          <div className="label">{t("Performance", "投放表现")}</div>
          <div style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.5, marginTop: 6 }}>
            {t(`Grade `, "评级 ")}<strong>{ad.grade}</strong> {t("overall", "(总评级)")} · Hook {ad.subGrades.hook} · CTR {ad.subGrades.ctr}.
            {t(" Spend ", " 花费 ")}{window.fmtMoney(ad.spend)} {t("at ROAS", "· ROAS")} {window.fmtRoas(ad.roas)}.
          </div>

          <div className="label" style={{ marginTop: 14 }}>{t("Personas", "人群画像")}</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: 6 }}>
            {ad.persona.map(p => <Pill key={p} variant="muted">{p}</Pill>)}
          </div>

          {/* The "其他动作" navigator that used to live here was duplicating
              the "Other completed iterations" strip below the main grid.
              Removed — there is now one clear place to switch between
              iterations on this ad. */}
        </aside>

        {/* Variants grid */}
        <section>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <div className="label">
              {kind === "copy_overlay" ? t("4 copy variants", "4 个文案变体") : t("4 image variants", "4 张图变体")} · {kind === "copy_overlay" ? t("ready for review", "可以查看了") : t("ready for review or push", "可以查看或推回投放")}
            </div>
            <div style={{ flex: 1 }} />

            <span className="label">{t("Sort", "排序")}</span>
            <select value={sort} onChange={e => setSort(e.target.value)}
              style={{ padding: "4px 8px", fontSize: 11, border: "1px solid var(--rule-strong)", borderRadius: 4, background: "var(--card)" }}>
              <option value="score">{t("By predicted lift", "按预测涨幅")}</option>
              <option value="direction">{t("By direction", "按方向")}</option>
              <option value="ratio">{t("By ratio", "按比例")}</option>
            </select>
          </div>

          <div className="card">
            <div className="card-h">
              <div>
                <div className="t-h2">{t("Why this might work", "为什么这样行得通")}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4, maxWidth: 580 }}>
                  {t(
                    "Your current ad does X · top performers in your cohort do Y · these variants try Y.",
                    "你当前的广告做的是 X · 你同类账户里表现最好的广告做的是 Y · 这几个变体在尝试 Y。"
                  )}
                </div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4, maxWidth: 580 }}>
                  {isZh && rec.exampleZh ? rec.exampleZh : rec.example}
                </div>
              </div>
              <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
                {rec.metrics.map(m => <Pill key={m} variant="muted">{m}</Pill>)}
              </div>
            </div>

            {comparing && selected.size >= 1 ? (
              <CompareView
                variants={sorted.filter(v => selected.has(v.id))}
                ad={ad}
                rec={rec}
                kind={kind}
                onExit={() => setComparing(false)}
              />
            ) : (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, padding: 14 }}>
                {sorted.map(v => (
                  <VariantCard key={v.id} v={v} ad={ad} rec={rec} kind={kind}
                    selected={selected.has(v.id)} starred={starred.has(v.id)}
                    onToggle={() => toggle(v.id)}
                    onStar={() => toggleStar(v.id)}
                  />
                ))}
              </div>
            )}
          </div>

          {/* Other completed iterations — compact navigator.
              Replaces the old verbose stacked card (full variant grid for
              every other iteration) AND the sidebar list. One clear place
              to switch between this ad's iterations, each chip-style card
              naming the rec + a quick «查看 →» action. */}
          {otherTasks.length > 0 && (
            <div style={{ marginTop: 28 }}>
              <div className="label" style={{ marginBottom: 10 }}>
                {t(`Other completed iterations on this ad · ${otherTasks.length}`, `这条广告上其他已完成的迭代 · ${otherTasks.length}`)}
              </div>
              <div style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
                gap: 10,
              }}>
                {otherTasks.map(tk => {
                  const r = ad.recs.find(x => x.id === tk.recId);
                  if (!r) return null;
                  const recTitle = isZh && r.titleZh ? r.titleZh : r.title;
                  const recShort = isZh && r.shortZh ? r.shortZh : r.short;
                  const kindLabel =
                    r.action_kind === "copy_overlay" ? t("Copy", "换文案") :
                    r.action_kind === "targeting_change" ? t("Targeting", "调受众") :
                    r.action_kind === "video_edit" ? t("Brief", "剪辑 brief") :
                    t("Image", "出图");
                  return (
                    <button
                      key={tk.id}
                      onClick={() => window.__viewVariants && window.__viewVariants(ad.id, tk.recId)}
                      style={{
                        textAlign: "left",
                        padding: "12px 14px",
                        background: "var(--card)",
                        border: "1px solid var(--rule)",
                        borderRadius: 4,
                        cursor: "pointer",
                        display: "flex", flexDirection: "column", gap: 6,
                        transition: "background .12s, border-color .12s",
                      }}
                      onMouseEnter={e => { e.currentTarget.style.background = "var(--bg-deep)"; e.currentTarget.style.borderColor = "var(--rule-strong)"; }}
                      onMouseLeave={e => { e.currentTarget.style.background = "var(--card)"; e.currentTarget.style.borderColor = "var(--rule)"; }}
                    >
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <span className="mono" style={{
                          fontSize: 9, padding: "1px 6px",
                          background: "var(--bg-deep)", color: "var(--ink-2)",
                          borderRadius: 2, letterSpacing: ".06em",
                        }}>{kindLabel}</span>
                        <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>
                          {window.relTime ? window.relTime(tk.completedAt) : ""}
                        </span>
                        <div style={{ flex: 1 }} />
                        <Icon name="arrow" size={11} />
                      </div>
                      <div className="t-h3" style={{ fontSize: 14 }}>{recTitle}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-3)", lineHeight: 1.45, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>
                        {recShort}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          )}
        </section>
      </div>

      {/* Sticky selection bar — selection-first; compare is a derived action */}
      {selected.size > 0 && (
        <div style={{
          position: "sticky", bottom: 16, marginTop: 24,
          background: "var(--ink)", color: "var(--bg)",
          borderRadius: 6, padding: "12px 18px",
          display: "flex", alignItems: "center", gap: 12,
          boxShadow: "0 10px 30px rgba(26,20,16,0.25)",
        }}>
          <div className="t-h2" style={{ color: "var(--bg)" }}>{selected.size} {t("selected", "已选中")}</div>
          <div style={{ fontSize: 11, opacity: 0.7 }}>
            {selected.size === 1
              ? t("Click Compare to see this variant next to the original.", "点「对比」就能跟原图并排看。")
              : t("Compare them against the original, then download or push.", "选中的变体跟原图一起对比、下载,或推回投放。")}
          </div>
          <div style={{ flex: 1 }} />
          <button className="btn sm ghost" style={{ color: "var(--bg)" }} onClick={() => setSelected(new Set())}>{t("Clear", "清空")}</button>
          <button
            className="btn sm"
            style={{ background: "transparent", color: "var(--bg)", borderColor: "rgba(255,255,255,0.2)" }}
            onClick={() => setComparing(true)}
            title={t(
              `Side-by-side: original + the ${selected.size} variant${selected.size > 1 ? "s" : ""} you picked.`,
              `并排对比:原图 + 你选中的 ${selected.size} 个变体。`
            )}
          >
            <Icon name="compare" size={12} />{t("Compare with original", "与原图对比")} ({selected.size})
          </button>
          <button
            className="btn sm"
            style={{ background: "transparent", color: "var(--bg)", borderColor: "rgba(255,255,255,0.2)" }}
            onClick={() => onPushedToPlatform && onPushedToPlatform(-selected.size)}
            title={t(
              "Download the selected variants as PNG/JPG (demo fires a toast).",
              "把选中的变体下载为 PNG / JPG(演示版本只会弹 toast 提示)。"
            )}
          >
            <Icon name="download" size={12} />{t("Download", "下载")}
          </button>
          <button
            className="btn sm"
            style={{ background: "var(--accent)", color: "var(--accent-ink)", borderColor: "var(--accent)" }}
            onClick={() => onPushedToPlatform(selected.size)}
            title={t(
              "Push selected variants back to Meta Ads Manager — they go live as a new ad set in the same campaign, A/B-tested against the original.",
              "把选中的变体推回 Meta 广告管理后台 —— 在原来的广告系列下新建一个广告组,跟原图做 A/B 对比投放。"
            )}
          >
            <Icon name="arrow" size={12} />{t("Push to ad platform", "推回投放平台")}
          </button>
        </div>
      )}
    </div>
  );
}

function VariantCard({ v, ad, rec, kind, selected, starred, compact, onToggle, onStar }) {
  const { Icon, MetricDelta, VariantPlaceholder } = window;
  const delta = Math.round(rec.primaryMetric.delta * v.deltaMul);
  return (
    <div
      onClick={onToggle}
      style={{
        position: "relative",
        border: selected ? "2px solid var(--accent)" : "1px solid var(--rule)",
        borderRadius: 4,
        background: "var(--card)",
        overflow: "hidden",
        cursor: "pointer",
        transition: "border-color .15s",
      }}>
      <div style={{ position: "relative", aspectRatio: kind === "copy_overlay" ? "4/3" : "2/3" }}>
        {kind === "copy_overlay"
          ? <CopyVariantPreview v={v} ad={ad} />
          : <window.AdCreative ad={ad} variant={v} w="100%" h="100%" />}
        <div style={{ position: "absolute", top: 8, right: 8 }}>
          <MetricDelta {...rec.primaryMetric} metricName={rec.primaryMetric.name} delta={delta} size="sm" />
        </div>
        {selected && (
          <div style={{ position: "absolute", top: 8, left: 8, background: "var(--accent)", color: "var(--accent-ink)", width: 22, height: 22, borderRadius: 4, display: "grid", placeItems: "center" }}>
            <Icon name="check" size={14} />
          </div>
        )}
        <div className="variant-hover" style={{
          position: "absolute", inset: 0,
          background: "linear-gradient(to top, rgba(26,20,16,0.75), transparent 50%)",
          opacity: 0, transition: "opacity .15s",
          display: "flex", flexDirection: "column", justifyContent: "flex-end", padding: 8,
          pointerEvents: "none",
        }}>
          <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
            <button
              className="btn sm"
              onClick={(e) => { e.stopPropagation(); onStar(); }}
              title={window.t ? window.t("Star this variant", "标星这个变体") : "Star"}
              style={{ background: "rgba(255,255,255,0.92)" }}
            >
              <Icon name={starred ? "starFill" : "star"} size={12} />
            </button>
          </div>
        </div>
      </div>
      {/* Caption row — keeps only tags + star indicator. The variant name and
          description are already shown inside the AdCreative itself, so the
          old big title + desc below the image have been removed to avoid the
          duplication users reported. */}
      <div style={{ padding: compact ? "6px 10px 8px" : "8px 12px 10px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6 }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 4, minWidth: 0 }}>
          {v.tags.map(tag => (
            <span key={tag} className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".05em" }}>·{tag}</span>
          ))}
        </div>
        {starred && <Icon name="starFill" size={12} />}
      </div>
      <style>{`
        .card div[style*="cursor: pointer"]:hover .variant-hover { opacity: 1; pointer-events: auto; }
      `}</style>
    </div>
  );
}

// CopyVariantPreview — renders a copy-overlay variant ON TOP of the source
// ad creative. Visually: the original AdCreative (so brand color + product
// shape are preserved) with a new copy-only overlay panel that swaps the
// headline and CTA. This is what «换文案 / copy_overlay» actually does in
// the real product: same image, different words.
function CopyVariantPreview({ v, ad }) {
  const isZh = window.getLang() === "zh";
  const copies = [
    { headEn: "Brew in 3 sec — anywhere.",         headZh: "3 秒一杯,随时随地。",       ctaEn: "Shop now →",    ctaZh: "立即购买 →" },
    { headEn: "Stop paying $2,000 / month.",       headZh: "别再每月花 2000 美金了。",   ctaEn: "Switch in 3 sec →", ctaZh: "3 秒切换 →" },
    { headEn: "Save 10 hours a week.",             headZh: "一周省 10 个小时。",         ctaEn: "See how →",     ctaZh: "看怎么做 →" },
    { headEn: "12 origins. One packet.",           headZh: "12 个产区,一盒搞定。",       ctaEn: "Try the flight →", ctaZh: "在家品鉴 →" },
  ];
  const c = copies[v.idx % 4];
  const head = isZh ? c.headZh : c.headEn;
  const cta  = isZh ? c.ctaZh  : c.ctaEn;

  return (
    <div style={{ position: "relative", width: "100%", height: "100%" }}>
      {/* Underlying ad creative — same brand color + product shape as the original */}
      <window.AdCreative ad={ad} w="100%" h="100%" />
      {/* Copy-only overlay — a translucent panel covering the lower 60% so
          the new headline visibly replaces the original one without changing
          the visual. Tag in the corner reminds reviewers it's a text swap. */}
      <div style={{
        position: "absolute",
        left: 12, right: 12, bottom: 12,
        padding: "14px 16px",
        background: "rgba(251,248,242,0.95)",
        border: "1px solid rgba(26,20,16,0.10)",
        borderRadius: 4,
        backdropFilter: "blur(4px)",
        WebkitBackdropFilter: "blur(4px)",
      }}>
        <div className="mono" style={{ fontSize: 9, color: "var(--ink-3)", letterSpacing: ".08em", marginBottom: 6, textTransform: "uppercase" }}>
          {isZh ? `换文案 · 0${v.idx + 1}` : `COPY OVERLAY · 0${v.idx + 1}`}
        </div>
        <div style={{
          fontFamily: "Source Serif 4, Georgia, serif",
          fontWeight: 600,
          fontSize: 17,
          lineHeight: 1.18,
          color: "var(--ink)",
        }}>{head}</div>
        <div style={{
          marginTop: 10,
          display: "inline-flex",
          alignItems: "center",
          padding: "4px 11px",
          background: "var(--ink)", color: "var(--bg)",
          borderRadius: 999,
          fontFamily: "IBM Plex Sans, sans-serif",
          fontSize: 10, fontWeight: 600,
        }}>{cta}</div>
      </div>
    </div>
  );
}

function CompareView({ variants, ad, rec, kind, onExit }) {
  const { Thumb, VariantPlaceholder, MetricDelta, Icon } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  return (
    <div style={{ padding: 14 }}>
      <div style={{ display: "flex", alignItems: "center", marginBottom: 8 }}>
        <div className="label">{t(`Side-by-side · original vs ${variants.length} variants`, `并排对比 · 原图 vs ${variants.length} 个变体`)}</div>
        <div style={{ flex: 1 }} />
        <button className="btn sm" onClick={onExit}>
          <Icon name="close" size={11} />{t("Exit compare", "退出对比")}
        </button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: `1fr ${variants.map(() => "1fr").join(" ")}`, gap: 12 }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginBottom: 6 }}>{t("ORIGINAL", "原图")}</div>
          <div style={{ aspectRatio: "2/3" }}>
            <window.AdCreative ad={ad} w="100%" h="100%" big />
          </div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 6 }}>
            {t("Baseline", "基线")} {rec.primaryMetric.baseline}{typeof rec.primaryMetric.baseline === "number" && rec.primaryMetric.baseline < 10 ? "%" : ""} · {rec.primaryMetric.name}
          </div>
        </div>
        {variants.map(v => {
          const delta = Math.round(rec.primaryMetric.delta * v.deltaMul);
          return (
            <div key={v.id}>
              <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
                <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{t("VARIANT", "变体")} · {String(v.idx + 1).padStart(2, "0")}</span>
                <MetricDelta {...rec.primaryMetric} metricName={rec.primaryMetric.name} delta={delta} size="sm" />
              </div>
              <div style={{ aspectRatio: kind === "copy_overlay" ? "4/3" : "2/3" }}>
                {kind === "copy_overlay"
                  ? <CopyVariantPreview v={v} ad={ad} />
                  : <window.AdCreative ad={ad} variant={v} w="100%" h="100%" />}
              </div>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 6 }}>
                {isZh ? `${rec.primaryMetric.baseline} → ${rec.primaryMetric.baseline + Math.round(rec.primaryMetric.baseline * delta / 100 * 100) / 100} · ${rec.primaryMetric.name}` : `${rec.primaryMetric.baseline} → ${rec.primaryMetric.baseline + Math.round(rec.primaryMetric.baseline * delta / 100 * 100) / 100} · ${rec.primaryMetric.name}`}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { Variants });
