/* global React, window */
// Right-side Detail drawer — Performance + AI Recommendation tabs.

const { useState, useEffect, useMemo } = React;

function DetailDrawer({ ad, open, onClose, completedTasksForAd, onIterate, onIterateBatch, initialTab, openSeq }) {
  const [tab, setTab] = useState(initialTab || "airec");
  const [batchMode, setBatchMode] = useState(false);
  const [selected, setSelected] = useState(new Set());
  const [expandedMore, setExpandedMore] = useState(false);
  const { Icon, Pill, Thumb, Grade, SubGrade } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const adHeadline = isZh && ad?.headlineZh ? ad.headlineZh : ad?.headline;
  const adSub = isZh && ad?.subZh ? ad.subZh : ad?.sub;

  // Whenever the drawer is re-opened (possibly with a different requested
  // initial tab), honor the caller's intent — "诊断/为什么?" lands on
  // Performance; the primary verb stays on AI Recommendation.
  // openSeq is bumped by App on every openAd() call so this effect re-fires
  // even when the same ad + same tab are re-clicked (otherwise the deps
  // wouldn't change and the tab wouldn't reset).
  useEffect(() => {
    if (open) setTab(initialTab || "airec");
  }, [open, ad?.id, initialTab, openSeq]);

  // Reset on close
  useEffect(() => {
    if (!open) {
      setSelected(new Set());
      setBatchMode(false);
      setExpandedMore(false);
    }
  }, [open, ad?.id]);

  if (!ad) return null;

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

  const completedRecIds = new Set((completedTasksForAd || []).map(t => t.recId));

  return (
    <>
      {/* Scrim no longer visually shows underlying content (drawer is full-
          screen now), but we keep it as a click target for Esc-equivalent
          dismiss + as a fade-in transition surface. */}
      <div className={"drawer-scrim " + (open ? "open" : "")} onClick={onClose} />
      <aside className={"drawer " + (open ? "open" : "")} aria-hidden={!open}>
        {/* Header — full-page detail now has an explicit back button +
            breadcrumb so users always know they can return to Radar. */}
        <div style={{ padding: "12px 24px", borderBottom: "1px solid var(--rule)", display: "flex", alignItems: "center", gap: 12, background: "var(--bg)" }}>
          <button
            className="btn ghost sm"
            onClick={onClose}
            title={t("Back to Radar (Esc)", "返回 Radar(Esc)")}
          >
            <Icon name="arrow" size={12} />
            <span style={{ transform: "scaleX(-1)", display: "inline-block", marginRight: 4 }}> </span>
            {t("Back to Radar", "返回 Radar")}
          </button>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)", letterSpacing: ".06em", textTransform: "uppercase" }}>
            / {t("Ad detail", "广告详情")} · {ad.code}
          </span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="t-h2" style={{ fontSize: 20, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", margin: 0 }}>
              {adHeadline}
            </div>
          </div>
          <Pill variant="muted">{t("Last 14 days", "最近 14 天")}</Pill>
        </div>

        {/* Body grid */}
        <div style={{ display: "grid", gridTemplateColumns: "minmax(220px, 30%) 1fr", flex: 1, minHeight: 0 }}>
          {/* LEFT */}
          <div style={{ borderRight: "1px solid var(--rule)", overflow: "auto", padding: "20px 22px" }}>
            <window.AdCreative ad={ad} w="100%" h={300} big />
            <div style={{ marginTop: 12 }}>
              <div className="label">{ad.code} · {ad.type === "video" ? t("Video", "视频") : t("Image", "图片")} · {t(`${ad.age} live`, `已投放 ${ad.age.replace(" weeks", " 周").replace(" week", " 周")}`)}</div>
              <div className="t-h3" style={{ marginTop: 4 }}>{adHeadline}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{adSub}</div>
            </div>

            <div style={{ marginTop: 18 }}>
              <div className="label" style={{ marginBottom: 6 }}>{t("Same series · 3 ads", "同系列 · 3 条广告")}</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {[0, 1, 2].map(i => {
                  const sib = window.ADS[(window.ADS.indexOf(ad) + i + 1) % window.ADS.length];
                  return (
                    <div key={i} style={{ display: "flex", gap: 8, padding: 6, border: "1px solid var(--rule)", borderRadius: 4, background: "var(--card)", alignItems: "center" }}>
                      <Thumb ad={sib} w={36} h={36} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{sib.code}</div>
                        <div style={{ fontSize: 11, lineHeight: 1.15, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{isZh && sib.headlineZh ? sib.headlineZh : sib.headline}</div>
                      </div>
                      <Grade value={sib.grade} size={22} />
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Quick metrics */}
            <div style={{ marginTop: 18, padding: 12, border: "1px solid var(--rule)", borderRadius: 4, background: "var(--card)" }}>
              <div style={{ marginBottom: 8 }}>
                <window.HelpHeader label={<span className="label">{t("Overall · A–D", "总评级 · A–D")}</span>}>
                  <div className="label" style={{ marginBottom: 6 }}>{t("How this score is computed", "这个评分是怎么算出来的")}</div>
                  <div style={{ marginBottom: 8, lineHeight: 1.55 }}>
                    {t(
                      "Percentile-vs-cohort, not absolute. Cohort = your other ads in the same vertical, format, and last ~14 days.",
                      "「跟同类样本比的百分位」,不是绝对阈值。同类样本 = 你账号下同类目、同格式、最近 14 天的其他广告。"
                    )}
                  </div>
                  <div style={{ fontFamily: "IBM Plex Mono, monospace", fontSize: 10, padding: "6px 8px", background: "var(--bg-deep)", borderRadius: 3, marginBottom: 8, color: "var(--ink-2)", lineHeight: 1.5 }}>
                    score = 0.40·z(ROAS) + 0.25·z(HOOK)<br/>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ 0.20·z(RET) + 0.15·z(CTR)
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 4, fontSize: 11, marginBottom: 8 }}>
                    <span><strong style={{ color: "var(--grade-a)" }}>A</strong> {t("≥ +1.0σ · top 10% · scale", "≥ +1.0σ · 前 10% · 加预算")}</span>
                    <span><strong style={{ color: "var(--grade-b)" }}>B</strong> {t("0 to +1.0σ · top 25% · keep", "0 到 +1.0σ · 前 25% · 维持投放")}</span>
                    <span><strong style={{ color: "var(--grade-c)" }}>C</strong> {t("−1.0σ to 0 · iterate soon", "−1.0σ 到 0 · 尽快迭代")}</span>
                    <span><strong style={{ color: "var(--grade-d)" }}>D</strong> {t("< −1.0σ · pause or rework", "< −1.0σ · 暂停或重做")}</span>
                  </div>
                  <div style={{ fontSize: 10, color: "var(--ink-3)", lineHeight: 1.5, borderTop: "1px solid var(--rule)", paddingTop: 6 }}>
                    {t(
                      "Refs: Meta Quality / Engagement / Conversion Rate Ranking · Google Ads Quality Score · Motion / Pencil creative scoring.",
                      "行业参照:Meta 的 Quality / Engagement / Conversion Rate Ranking · Google Ads Quality Score · Motion / Pencil 等创意分析工具。"
                    )}
                  </div>
                </window.HelpHeader>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <Grade value={ad.grade} size={36} />
                <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1fr 1fr", columnGap: 8, rowGap: 4 }}>
                  <SubGrade label="ROAS" value={ad.subGrades.roas} />
                  <SubGrade label="HOOK" value={ad.subGrades.hook} />
                  <SubGrade label="RET"  value={ad.subGrades.retention} />
                  <SubGrade label="CTR"  value={ad.subGrades.ctr} />
                </div>
              </div>
              <div className="hr" style={{ margin: "10px 0" }} />
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11 }}>
                <span style={{ color: "var(--ink-3)" }}>{t("Spend", "花费")}</span>
                <span className="mono">{window.fmtMoney(ad.spend)}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginTop: 4 }}>
                <span style={{ color: "var(--ink-3)" }}>ROAS</span>
                <span className="mono">{window.fmtRoas(ad.roas)}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginTop: 4 }}>
                <span style={{ color: "var(--ink-3)" }}>{t("Impressions", "曝光量")}</span>
                <span className="mono">{ad.impressions.toLocaleString()}</span>
              </div>
            </div>
          </div>

          {/* RIGHT */}
          <div style={{ overflow: "auto", display: "flex", flexDirection: "column", minHeight: 0 }}>
            <div className="tabs" style={{ padding: "0 24px", borderBottom: "1px solid var(--rule)" }}>
              <div className={"tab " + (tab === "perf" ? "active" : "")} onClick={() => setTab("perf")}>{t("Performance", "投放表现")}</div>
              <div className={"tab " + (tab === "airec" ? "active" : "")} onClick={() => setTab("airec")}>
                {t("AI Recommendation", "AI 建议")}
                <span className="tab-count">{ad.type === "video" ? "—" : ad.recs.length}</span>
              </div>
            </div>

            <div style={{ flex: 1, overflow: "auto", padding: "20px 24px 100px" }}>
              {tab === "perf" && <PerfTab ad={ad} />}
              {tab === "airec" && (
                ad.type === "video"
                  ? <VideoEmpty ad={ad} onIterate={onIterate} />
                  : <AiRecTab ad={ad}
                      selected={selected} toggle={toggle}
                      batchMode={batchMode} setBatchMode={setBatchMode}
                      expandedMore={expandedMore} setExpandedMore={setExpandedMore}
                      completedRecIds={completedRecIds}
                      onIterate={(recId) => onIterate(ad.id, [recId])}
                    />
              )}
            </div>

            {/* Sticky batch action bar — only when batch mode is on AND user has selected */}
            {tab === "airec" && ad.type !== "video" && batchMode && selected.size > 0 && (
              <div style={{
                position: "sticky", bottom: 0,
                padding: "14px 24px",
                borderTop: "1px solid var(--rule-strong)",
                background: "var(--card)",
                display: "flex", alignItems: "center", gap: 12,
                boxShadow: "0 -8px 24px rgba(26,20,16,0.08)",
              }}>
                <div className="t-h2">
                  {t("Run", "同时跑")} <em style={{ color: "var(--accent)", fontStyle: "italic" }}>{selected.size}</em> {t("moves in parallel", "条建议")}
                </div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>
                  {t("Mixed action kinds will branch to their own flows.", "不同类型的建议会走各自对应的流程。")}
                </div>
                <div style={{ flex: 1 }} />
                <button className="btn sm ghost" onClick={() => setSelected(new Set())}>{t("Clear", "清空")}</button>
                <button className="btn primary" onClick={() => onIterateBatch(ad.id, Array.from(selected))}>
                  <Icon name="bolt" size={12} />
                  {t(`Run ${selected.size} moves`, `运行 ${selected.size} 条建议`)}
                </button>
              </div>
            )}
          </div>
        </div>
      </aside>
    </>
  );
}

function PerfTab({ ad }) {
  const { Pill } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  return (
    <div>
      <div className="label">{t("Performance summary", "投放表现概览")}</div>
      <p style={{ fontSize: 14, lineHeight: 1.55, color: "var(--ink-2)", margin: "6px 0 18px", maxWidth: 640 }}>
        {ad.perfText}
      </p>

      <div className="label">{t("Persona", "人群画像")}</div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, margin: "6px 0 18px" }}>
        {ad.persona.map(p => <Pill key={p} variant="muted">{p}</Pill>)}
      </div>

      <div className="label">{t("Top issues identified", "识别到的关键问题")}</div>
      <ol style={{ paddingLeft: 18, margin: "8px 0 18px", color: "var(--ink-2)", fontSize: 13, lineHeight: 1.55 }}>
        {ad.topIssues.map((it, i) => <li key={i} style={{ marginBottom: 4 }}>{it}</li>)}
      </ol>

      <div className="label">{t("Recommendations preview", "建议预览")}</div>
      <div style={{ marginTop: 8 }}>
        {ad.recs.slice(0, 4).map((r, i) => (
          <div key={r.id} style={{ display: "flex", gap: 14, padding: "10px 0", borderBottom: i < 3 ? "1px solid var(--rule)" : "none" }}>
            <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", width: 22 }}>{String(r.priority).padStart(2, "0")}</div>
            <div>
              <div className="t-h3">{isZh && r.titleZh ? r.titleZh : r.title}</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{isZh && r.shortZh ? r.shortZh : r.short}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AiRecTab({ ad, selected, toggle, batchMode, setBatchMode, expandedMore, setExpandedMore, completedRecIds, onIterate }) {
  const { Pill, Check, Icon, Thumb, MetricDelta } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const hero = ad.recs[0];
  const others = ad.recs.slice(1);

  return (
    <div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14 }}>
        <div>
          <div className="label">{t("Top move · ranked by predicted lift", "主推动作 · 按预测涨幅排序")}</div>
          <div className="t-h1" style={{ fontSize: 28 }}>{t("What to try next.", "下一步该试什么。")}</div>
        </div>
        <button className="btn sm" onClick={() => { setBatchMode(b => !b); setExpandedMore(true); }}>
          {batchMode ? t("Single mode", "单条模式") : t("Run multiple moves", "同时跑多条")}
        </button>
      </div>

      {/* HERO REC */}
      <HeroRec rec={hero} ad={ad}
        batchMode={batchMode}
        selected={selected.has(hero.id)}
        toggle={() => toggle(hero.id)}
        completed={completedRecIds.has(hero.id)}
        onIterate={() => onIterate(hero.id)}
        onNotUseful={(done) => window.__openFeedback && window.__openFeedback(hero, ad, done)}
        onMarkUseful={() => window.__markUseful && window.__markUseful(hero, ad)}
      />

      {/* OTHER MOVES */}
      <div style={{ marginTop: 16 }}>
        <button onClick={() => setExpandedMore(e => !e)} style={{
          width: "100%", padding: "12px 14px", border: "1px solid var(--rule)",
          borderRadius: 4, background: "var(--card)",
          display: "flex", alignItems: "center", gap: 10,
          cursor: "pointer", textAlign: "left",
        }}>
          <Icon name={expandedMore ? "chevDown" : "chev"} size={12} />
          <span className="t-h3" style={{ fontSize: 15 }}>{t(`${others.length} more moves to consider`, `还有 ${others.length} 条建议可考虑`)}</span>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>
            {others.map(r => (isZh && r.titleZh ? r.titleZh : r.title).split(" ")[0]).join(" · ")}
          </span>
        </button>

        {expandedMore && (
          <div style={{ marginTop: 8, border: "1px solid var(--rule)", borderRadius: 4, background: "var(--card)" }}>
            {others.map((r, i) => {
              const isOn = selected.has(r.id);
              const done = completedRecIds.has(r.id);
              return (
                <div key={r.id} style={{
                  display: "grid", gridTemplateColumns: batchMode ? "28px 1fr 200px" : "1fr 200px",
                  padding: "14px 16px",
                  borderBottom: i < others.length - 1 ? "1px solid var(--rule)" : "none",
                  alignItems: "center",
                  gap: 12,
                  background: isOn ? "var(--accent-tint)" : "transparent",
                  transition: "background .15s",
                }}>
                  {batchMode && <Check on={isOn} onClick={() => toggle(r.id)} />}
                  <div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{String(r.priority).padStart(2, "0")}</span>
                      <div className="t-h3">{isZh && r.titleZh ? r.titleZh : r.title}</div>
                      <ActionKindBadge kind={r.action_kind} />
                    </div>
                    <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>{isZh && r.shortZh ? r.shortZh : r.short}</div>
                    <div style={{ marginTop: 6 }}>
                      <MetricDelta {...r.primaryMetric} metricName={r.primaryMetric.name} delta={r.primaryMetric.delta} size="sm" />
                    </div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    {done ? (
                      <button className="btn sm" onClick={() => window.__viewVariants && window.__viewVariants(ad.id, r.id)}>
                        {t("View output", "查看产出")} <Icon name="arrow" size={11} />
                      </button>
                    ) : (
                      <button className={"btn sm " + (batchMode ? "" : "primary")} onClick={() => batchMode ? toggle(r.id) : onIterate(r.id)}>
                        {batchMode
                          ? (isOn ? t("Selected", "已选中") : t("Select", "选中"))
                          : <><Icon name="bolt" size={11} />{ctaShort(r)}</>}
                      </button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function HeroRec({ rec, ad, batchMode, selected, toggle, completed, onIterate, onNotUseful, onMarkUseful }) {
  const { Pill, Check, Icon, MetricDelta } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const recTitle = isZh && rec.titleZh ? rec.titleZh : rec.title;
  const recWhy = isZh && rec.whyZh ? rec.whyZh : rec.why;
  const recExample = isZh && rec.exampleZh ? rec.exampleZh : rec.example;
  const recCta = isZh && rec.cta_labelZh ? rec.cta_labelZh : rec.cta_label;
  return (
    <div style={{
      padding: "22px 24px",
      border: "1px solid var(--rule)",
      borderRadius: 6,
      background: "var(--card)",
      position: "relative",
      boxShadow: selected ? "0 0 0 2px var(--accent)" : "none",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
        <span className="label" style={{ color: "var(--accent)" }}>{t("★ Top move · priority 01", "★ 主推动作 · 优先级 01")}</span>
        <div style={{ flex: 1 }} />
        <ActionKindBadge kind={rec.action_kind} large />
      </div>

      <div className="t-h1" style={{ fontSize: 30 }}>{recTitle}</div>
      <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55, marginTop: 10, maxWidth: 640 }}>
        {recWhy}
      </div>

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

      <div style={{ display: "flex", gap: 14, alignItems: "flex-start", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
        <div style={{ flex: "1 1 360px", minWidth: 0 }}>
          <div className="label" style={{ marginBottom: 6 }}>{t("Why this might work", "为什么这样行得通")}</div>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55, maxWidth: 460 }}>
            {recExample}
          </div>
        </div>
        <div style={{ minWidth: 180 }}>
          <div className="label" style={{ marginBottom: 6 }}>{t("Predicted lift", "预测涨幅")}</div>
          <MetricDelta {...rec.primaryMetric} metricName={rec.primaryMetric.name} delta={rec.primaryMetric.delta} />
          <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 6 }}>
            {rec.metrics.join(" · ")} · {rec.primaryMetric.basis} {t("similar creatives.", "条相似创意")}
          </div>
        </div>
      </div>

      <div style={{ marginTop: 16, display: "flex", alignItems: "center", gap: 10 }}>
        {batchMode ? (
          <button className="btn primary" onClick={toggle}>
            <Check on={selected} onClick={toggle} label="select" />
            <span style={{ marginLeft: 6 }}>{selected ? t("Selected for batch", "已加入批量") : t("Add to batch", "加入批量")}</span>
          </button>
        ) : completed ? (
          <button className="btn primary" onClick={() => window.__viewVariants && window.__viewVariants(ad.id, rec.id)}>
            <Icon name="arrow" size={12} />{t("View output", "查看产出")}
          </button>
        ) : (
          <button className="btn primary" onClick={onIterate} style={{ padding: "10px 16px", fontSize: 13 }}>
            <Icon name="bolt" size={13} />
            {recCta}
          </button>
        )}
        <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>
          {actionKindEta(rec.action_kind)}
        </span>
      </div>

      {/* M4 (A-4): Actionable feedback footer — replaces dead-end thumbs */}
      {!batchMode && window.FeedbackWidget && (
        <div style={{
          marginTop: 18,
          paddingTop: 14,
          borderTop: "1px dashed var(--rule-strong)",
          display: "flex",
          justifyContent: "flex-end",
        }}>
          <window.FeedbackWidget
            rec={rec}
            ad={ad}
            onUseful={onMarkUseful}
            onNotUseful={onNotUseful}
          />
        </div>
      )}
    </div>
  );
}

function ctaShort(r) {
  const t = window.t;
  if (r.action_kind === "copy_overlay") return t("Copy variants", "文案变体");
  if (r.action_kind === "targeting_change") return t("Apply change", "应用调整");
  if (r.action_kind === "video_edit") return t("Export brief", "导出 brief");
  return t("Generate images", "生成图片");
}

function actionKindEta(kind) {
  const t = window.t;
  if (kind === "copy_overlay") return t("~ 20s · 4 copy variants", "约 20 秒 · 4 个文案变体");
  if (kind === "targeting_change") return t("~ 5s · syncs with Meta Ads Manager", "约 5 秒 · 同步到 Meta 广告管理后台");
  if (kind === "video_edit") return t("~ 10s · exports a brief PDF", "约 10 秒 · 导出 brief PDF");
  return t("~ 40s · 4 image variants", "约 40 秒 · 4 张图变体");
}

function ActionKindBadge({ kind, large }) {
  const t = window.useT();
  const map = {
    image_gen:        { label: t("Image gen", "出图"),        color: "var(--accent)" },
    copy_overlay:     { label: t("Copy overlay", "换文案"),   color: "var(--grade-b)" },
    targeting_change: { label: t("Targeting", "调受众"),      color: "var(--status-running)" },
    video_edit:       { label: t("Video brief", "视频 brief"),color: "var(--grade-d)" },
  };
  const m = map[kind] || map.image_gen;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      padding: large ? "3px 8px" : "1px 6px",
      borderRadius: 3,
      background: "var(--bg-deep)",
      fontFamily: "IBM Plex Mono, monospace",
      fontSize: large ? 10 : 9,
      letterSpacing: ".08em",
      textTransform: "uppercase",
      color: m.color,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: m.color }} />
      {m.label}
    </span>
  );
}

function VideoEmpty({ ad, onIterate }) {
  const { Icon, MetricDelta } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  return (
    <div>
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 12 }}>
        <Icon name="video" size={18} />
        <div className="t-h1" style={{ fontSize: 28 }}>{t("Video iteration is on the roadmap.", "视频版本迭代在路线图上。")}</div>
      </div>
      <p style={{ fontSize: 13, color: "var(--ink-3)", lineHeight: 1.55, maxWidth: 540 }}>
        {t(
          "We can't regenerate video variants yet — but this ad still has actionable recommendations. Pick one of the two paths below.",
          "我们还不能直接重新生成视频变体 —— 但这条广告依然有可执行的建议。下面两条路径任选一条。"
        )}
      </p>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 18 }}>
        <div className="card">
          <div className="card-b">
            <div className="label">{t("Option A", "方案 A")}</div>
            <div className="t-h3" style={{ marginTop: 4 }}>{t("Apply suggestion to copy / overlay", "把建议应用到文案 / 字幕叠加")}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 6 }}>
              {t(
                "Generate new ad copy + text overlay you can drop onto the existing video in your editor. Takes ~20s.",
                "生成新的广告文案 + 字幕叠加,你可以直接拖进剪辑软件叠到现有视频上。大约 20 秒。"
              )}
            </div>
            <button className="btn sm" style={{ marginTop: 12 }} onClick={() => onIterate(ad.id, [ad.recs[0].id])}>
              <Icon name="bolt" size={12} /> {t("Generate copy", "生成文案")}
            </button>
          </div>
        </div>
        <div className="card">
          <div className="card-b">
            <div className="label">{t("Option B", "方案 B")}</div>
            <div className="t-h3" style={{ marginTop: 4 }}>{t("Brief a video re-cut", "出一份重剪 brief")}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 6 }}>
              {t(
                "Export the recommendations as a brief for your video editor (Premiere / CapCut). We do the writing.",
                "把建议导成一份给视频剪辑师(Premiere / 剪映)的工作说明。我们负责写,你拿去用。"
              )}
            </div>
            <button
              className="btn sm"
              style={{ marginTop: 12 }}
              onClick={() => {
                if (typeof window.__pushToast === "function") {
                  window.__pushToast(t(
                    `Brief exported for ${ad.code} · sent to your shared drive`,
                    `${ad.code} 的 brief 已导出 · 已发送到共享盘`
                  ), "success");
                }
              }}
            >
              <Icon name="download" size={12} /> {t("Export brief", "导出 brief")}
            </button>
          </div>
        </div>
      </div>

      <div className="hr" style={{ margin: "24px 0" }} />
      <div className="label">{t("Recommendations (text only)", "建议(仅文字)")}</div>
      <div style={{ marginTop: 8 }}>
        {ad.recs.map(r => (
          <div key={r.id} style={{ padding: "12px 0", borderBottom: "1px solid var(--rule)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <div className="t-h3">{isZh && r.titleZh ? r.titleZh : r.title}</div>
              <MetricDelta {...r.primaryMetric} metricName={r.primaryMetric.name} delta={r.primaryMetric.delta} size="sm" />
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{isZh && r.exampleZh ? r.exampleZh : r.example}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { DetailDrawer });
