/* global React, window */
// M3 (K-2): Iteration history screen — lives under Analytics in the sidebar,
// reachable also from Tasks panel deep-links. Shows all completed iterations
// grouped by source ad, with a clear «From Radar» breadcrumb on every variant.

const { useMemo } = React;

function IterationHistory({ tasks, ads, onOpenTask, onBackToRadar }) {
  const { Thumb, Pill, Icon, relTime } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";

  // Group completed tasks by adId
  const grouped = useMemo(() => {
    const m = {};
    tasks
      .filter(t => t.status === "completed")
      .forEach(t => {
        const ad = ads.find(a => a.id === t.adId);
        if (!ad) return;
        (m[t.adId] = m[t.adId] || { ad, tasks: [] }).tasks.push(t);
      });
    return Object.values(m).sort((a, b) => b.tasks.length - a.tasks.length);
  }, [tasks, ads]);

  const totalIterations = grouped.reduce((s, g) => s + g.tasks.length, 0);

  return (
    <div style={{ padding: "0 24px 60px" }}>
      <div style={{ padding: "32px 0 20px", display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 32, flexWrap: "wrap" }}>
        <div style={{ minWidth: 0, flex: "1 1 320px" }}>
          <div className="eyebrow">{t("Analytics · Iteration history", "数据分析 · 迭代历史")}</div>
          <h1 className="t-display" style={{ margin: "6px 0 0" }}>
            <em>{t("Iteration history.", "迭代历史。")}</em> {t(`${totalIterations} variants across ${grouped.length} ads.`, `${totalIterations} 个变体,横跨 ${grouped.length} 条广告。`)}
          </h1>
          <div style={{ marginTop: 10, color: "var(--ink-3)", fontSize: 13, maxWidth: 720 }}>
            {t(
              "Every iteration that started in Radar lives here — grouped by the source ad, with the same metric deltas and confidence dots you saw on the Variants page. Click any group to compare or push more variants to platform.",
              "所有从 Radar 触发的迭代都归在这里 —— 按源广告分组,跟变体页一样有指标涨幅和置信度小点。点任意一组可以对比,或者把更多变体推回投放平台。"
            )}
          </div>
        </div>
        <button className="btn" onClick={onBackToRadar}>
          <Icon name="arrow" size={11} />
          <span style={{ marginLeft: 4, transform: "scaleX(-1)", display: "inline-block" }}> </span>
          {t("Back to Radar", "返回 Radar")}
        </button>
      </div>

      <div className="hr" />

      {grouped.length === 0 ? (
        <div className="empty" style={{ marginTop: 32 }}>
          <div className="t-h3" style={{ marginBottom: 6 }}>{t("No iterations yet.", "暂无迭代记录。")}</div>
          <div>{t("Open the Radar drawer on any image ad and run an Iterate or Refresh recommendation.", "在 Radar 里打开任意一条图片广告的详情抽屉,跑一条「迭代」或「换素材」建议即可。")}</div>
        </div>
      ) : (
        <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 18 }}>
          {grouped.map(group => (
            <AdHistoryCard key={group.ad.id} ad={group.ad} tasks={group.tasks} onOpenTask={onOpenTask} />
          ))}
        </div>
      )}
    </div>
  );
}

function AdHistoryCard({ ad, tasks, onOpenTask }) {
  const { Thumb, relTime, Icon } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  // sort newest first
  const sorted = [...tasks].sort((a, b) => (b.completedAt || 0) - (a.completedAt || 0));
  return (
    <div className="card" style={{ padding: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
        <Thumb ad={ad} w={64} h={64} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="label" style={{ marginBottom: 2 }}>
            {t("From Radar", "来自 Radar")} · {ad.code}
          </div>
          <div className="t-h2" style={{ marginBottom: 2 }}>{isZh && ad.headlineZh ? ad.headlineZh : ad.headline}</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>
            {sorted.length} {t(sorted.length > 1 ? "iterations" : "iteration", "次迭代")} · {t("most recent", "最近一次")} {relTime(sorted[0].completedAt)}
          </div>
        </div>
      </div>
      <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 10 }}>
        {sorted.map(tk => {
          const kindLabel = tk.action_kind === "copy_overlay" ? t("Copy variants", "文案变体")
            : tk.action_kind === "targeting_change" ? t("Targeting change", "受众调整")
            : tk.action_kind === "video_edit" ? t("Brief", "剪辑 brief")
            : t("Image variants", "图片变体");
          const status = tk.pushed ? t("PUSHED", "已发布") : t("DRAFT", "草稿");
          return (
            <button
              key={tk.id}
              onClick={() => onOpenTask(tk)}
              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: 8 }}>
                <span className="mono" style={{ fontSize: 9, padding: "1px 5px", background: "var(--bg-deep)", color: "var(--ink-2)", borderRadius: 2 }}>{kindLabel}</span>
                <span className="mono" style={{ fontSize: 9, padding: "1px 5px", background: tk.pushed ? "var(--grade-a)" : "var(--bg-deep)", color: tk.pushed ? "var(--bg)" : "var(--ink-3)", borderRadius: 2, letterSpacing: ".08em" }}>{status}</span>
              </div>
              <div className="t-h3" style={{ fontSize: 14 }}>{window.localizedRecTitle(tk)}</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>
                {t("Completed", "完成于")} {relTime(tk.completedAt)} · {t("click to open", "点击打开")}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { IterationHistory });
