/* global React, window */
// Image Ads — standalone generation projects (Clone-S / IT-RID / Playground).
// Post Move 10, Radar iterations live under Analytics > Iteration history,
// so this page is now the home for non-Radar-triggered work.

const { useState, useMemo } = React;

const SOURCE_LABELS = {
  "clone-s": { en: "Clone-S", zh: "Clone-S" },
  "it-rid":  { en: "IT-RID",  zh: "IT-RID" },
  "playground": { en: "Playground", zh: "Playground" },
};
const SOURCE_COLORS = {
  "clone-s":   "#2A5FD1",
  "it-rid":    "#3D7A4F",
  "playground":"#D14A1F",
};

function ImageAds({ projects, brands, onBackToRadar }) {
  const [filter, setFilter] = useState("all"); // all | clone-s | it-rid | playground
  const [activeProject, setActiveProject] = useState(null);
  const { Icon, Thumb, VariantPlaceholder } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";

  const filtered = useMemo(() => {
    if (filter === "all") return projects;
    return projects.filter(p => p.source === filter);
  }, [projects, filter]);

  const counts = {
    all: projects.length,
    "clone-s": projects.filter(p => p.source === "clone-s").length,
    "it-rid":  projects.filter(p => p.source === "it-rid").length,
    "playground": projects.filter(p => p.source === "playground").length,
  };

  if (activeProject) {
    return <ProjectDetail
      project={activeProject}
      brand={brands.find(b => b.name === activeProject.brand)}
      onBack={() => setActiveProject(null)}
      onBackToRadar={onBackToRadar}
    />;
  }

  return (
    <div style={{ padding: "0 24px 60px" }}>
      <div style={{ padding: "32px 0 20px" }}>
        <div className="eyebrow">{t("Creation · Image Ads · Standalone projects", "创意生成 · 图片广告 · 独立项目")}</div>
        <h1 className="t-display" style={{ margin: "6px 0 0" }}>
          <em>Image Ads.</em> {t(`${projects.length} projects across ${new Set(projects.map(p => p.brand)).size} brands.`, `${projects.length} 个项目,横跨 ${new Set(projects.map(p => p.brand)).size} 个品牌。`)}
        </h1>
        <div style={{ marginTop: 10, color: "var(--ink-3)", fontSize: 13, maxWidth: 720 }}>
          {t(
            "Standalone generation projects — Clone-S, IT-RID, and Playground output. Iterations triggered from Radar now live under",
            "独立发起的生成项目 —— 来自 Clone-S、IT-RID、Playground 的产物。从 Radar 触发的迭代现在归到"
          )}{" "}
          <strong>{t("Analytics → Iteration history", "数据分析 → 迭代历史")}</strong> {t("instead (Move 10).", "(Move 10 的产物)。")}
        </div>
      </div>

      <div className="hr" />

      <div style={{ display: "flex", padding: "8px 0", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
        {[
          { id: "all", label: t("All projects", "全部项目") },
          { id: "clone-s", label: "Clone-S" },
          { id: "it-rid", label: "IT-RID" },
          { id: "playground", label: t("Playground", "实验场") },
        ].map(f => (
          <button
            key={f.id}
            onClick={() => setFilter(f.id)}
            className={"tab " + (filter === f.id ? "active" : "")}
            style={{ padding: "8px 14px" }}
          >
            <span>{f.label}</span>
            <span className="tab-count">{counts[f.id]}</span>
          </button>
        ))}
        <div style={{ flex: 1 }} />
      </div>

      <div style={{ marginTop: 18, display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 12 }}>
        {filtered.length === 0 ? (
          <div className="empty">
            <div className="t-h3" style={{ marginBottom: 4 }}>{t(`No ${SOURCE_LABELS[filter]?.en || filter} projects yet.`, "暂无项目。")}</div>
            <div>{t("Open Playground or Radar to start something.", "在 Playground 或 Radar 里发起一个吧。")}</div>
          </div>
        ) : (
          filtered.map(p => (
            <ProjectCard key={p.id} project={p} onClick={() => setActiveProject(p)} />
          ))
        )}
      </div>

      <div style={{ marginTop: 28, textAlign: "center", color: "var(--ink-3)", fontSize: 11 }}>
        <button className="btn ghost sm" onClick={onBackToRadar}>← {t("Back to Radar", "返回 Radar")}</button>
      </div>
    </div>
  );
}

function ProjectCard({ project, onClick }) {
  const { Icon } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const sourceColor = SOURCE_COLORS[project.source];
  const sourceLabel = SOURCE_LABELS[project.source]?.[isZh ? "zh" : "en"] || project.source;
  return (
    <button
      onClick={onClick}
      style={{
        textAlign: "left",
        padding: 16,
        background: "var(--card)",
        border: "1px solid var(--rule)",
        borderRadius: 6,
        cursor: "pointer",
        display: "flex",
        flexDirection: "column",
        gap: 10,
        transition: "border-color .15s, background .15s",
      }}
      onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--rule-strong)"; e.currentTarget.style.background = "var(--bg-deep)"; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--rule)"; e.currentTarget.style.background = "var(--card)"; }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
        <span className="mono" style={{
          fontSize: 9, padding: "2px 7px",
          background: sourceColor, color: "var(--bg)",
          borderRadius: 2, letterSpacing: ".08em", fontWeight: 600,
        }}>{sourceLabel}</span>
        <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{project.brand}</span>
        <span className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>· {isZh && project.createdAtZh ? project.createdAtZh : project.createdAt}</span>
      </div>
      <div className="t-h3" style={{ fontSize: 16, lineHeight: 1.3 }}>{isZh && project.titleZh ? project.titleZh : project.title}</div>
      <div style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.55 }}>{isZh && project.descriptionZh ? project.descriptionZh : project.description}</div>
      {/* Mini thumbnails strip */}
      <div style={{ display: "flex", gap: 4, marginTop: 4 }}>
        {Array.from({ length: Math.min(project.variants, 4) }).map((_, i) => (
          <div key={i} style={{
            flex: 1,
            aspectRatio: "1",
            background: `linear-gradient(135deg, ${sourceColor}33 0%, ${sourceColor}11 100%)`,
            border: `1px solid ${sourceColor}55`,
            borderRadius: 2,
            display: "grid", placeItems: "center",
            fontFamily: "IBM Plex Mono, monospace",
            fontSize: 8, color: sourceColor, fontWeight: 600,
          }}>v{i + 1}</div>
        ))}
        {project.variants > 4 && (
          <div style={{
            flex: 1, aspectRatio: "1",
            background: "var(--bg-deep)",
            border: "1px dashed var(--rule)",
            borderRadius: 2,
            display: "grid", placeItems: "center",
            fontFamily: "IBM Plex Mono, monospace",
            fontSize: 9, color: "var(--ink-3)",
          }}>+{project.variants - 4}</div>
        )}
      </div>
      <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 2 }}>
        {project.variants} {t("variants · click to open →", "个变体 · 点击打开 →")}
      </div>
    </button>
  );
}

function ProjectDetail({ project, brand, onBack, onBackToRadar }) {
  const { Icon, VariantPlaceholder } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const sourceColor = SOURCE_COLORS[project.source];
  const sourceLabel = SOURCE_LABELS[project.source]?.[isZh ? "zh" : "en"] || project.source;

  return (
    <div style={{ padding: "0 24px 60px" }}>
      <div style={{ padding: "24px 0 14px" }}>
        <button className="btn sm ghost" onClick={onBack}>
          ← {t("All projects", "全部项目")}
        </button>
      </div>
      <div style={{ padding: "10px 0 20px", display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 18 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
            <span className="mono" style={{
              fontSize: 9, padding: "2px 7px",
              background: sourceColor, color: "var(--bg)",
              borderRadius: 2, letterSpacing: ".08em", fontWeight: 600,
            }}>{sourceLabel}</span>
            <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{project.brand} · {isZh && project.createdAtZh ? project.createdAtZh : project.createdAt}</span>
          </div>
          <h1 className="t-h1" style={{ margin: 0 }}>{isZh && project.titleZh ? project.titleZh : project.title}</h1>
          <div style={{ marginTop: 10, color: "var(--ink-2)", fontSize: 13, maxWidth: 720, lineHeight: 1.6 }}>
            {isZh && project.descriptionZh ? project.descriptionZh : project.description}
          </div>
        </div>
        <div style={{ display: "inline-flex", gap: 8 }}>
          <button
            className="btn"
            onClick={() => {
              if (typeof window.__pushToast === "function") {
                window.__pushToast(t(
                  `Started downloading ${project.variants} variants from «${isZh && project.titleZh ? project.titleZh : project.title}» (demo).`,
                  `开始下载「${isZh && project.titleZh ? project.titleZh : project.title}」的 ${project.variants} 个变体(演示)。`
                ), "success");
              }
            }}
          >
            <Icon name="download" size={12} /> {t("Download all", "全部下载")}
          </button>
          <button
            className="btn primary"
            onClick={() => {
              if (typeof window.__pushToast === "function") {
                window.__pushToast(t(
                  `Pushed «${isZh && project.titleZh ? project.titleZh : project.title}» to Meta Ads Manager as a new test set.`,
                  `已把「${isZh && project.titleZh ? project.titleZh : project.title}」推回 Meta 广告管理后台,新建一个测试广告组。`
                ), "success");
              }
            }}
          >
            <Icon name="arrow" size={12} /> {t("Push to platform", "推回投放平台")}
          </button>
        </div>
      </div>

      <div className="hr" />

      <div style={{
        marginTop: 20,
        display: "grid",
        gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))",
        gap: 12,
      }}>
        {Array.from({ length: project.variants }).map((_, i) => (
          <div key={i} style={{
            border: "1px solid var(--rule)",
            borderRadius: 4,
            background: "var(--card)",
            overflow: "hidden",
          }}>
            <div style={{ position: "relative", aspectRatio: "2/3" }}>
              <VariantPlaceholder
                v={{ idx: i, name: `Variant ${i + 1}`, desc: "", tags: [] }}
                w={220} h={330}
                accent={sourceColor}
              />
              <div style={{
                position: "absolute", top: 8, right: 8,
                padding: "2px 7px",
                background: "var(--card)",
                border: "1px solid var(--rule-strong)",
                borderRadius: 3,
                fontFamily: "IBM Plex Mono, monospace",
                fontSize: 10, fontWeight: 600,
                color: "var(--ink-2)",
              }}>v{i + 1}</div>
            </div>
            <div style={{ padding: "10px 12px" }}>
              <div className="t-h3" style={{ fontSize: 14, lineHeight: 1.3 }}>{t("Variant", "变体")} {i + 1}</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 4 }}>
                {project.source}/{project.id}/v{i + 1}
              </div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 28, textAlign: "center", color: "var(--ink-3)", fontSize: 11 }}>
        <button className="btn ghost sm" onClick={onBackToRadar}>← {t("Back to Radar", "返回 Radar")}</button>
      </div>
    </div>
  );
}

Object.assign(window, { ImageAds });
