/* global React, window */
// Action modals — one per action_kind. The router picks based on the recs being run.

const { useState, useEffect } = React;

function ActionModal({ open, ad, recIds, onClose, onConfirm }) {
  if (!open || !ad) return null;
  const recs = (ad.recs || []).filter(r => recIds.includes(r.id));
  // Single-rec routing
  if (recs.length === 1) {
    const r = recs[0];
    if (r.action_kind === "targeting_change") {
      return <TargetingModal open={open} ad={ad} rec={r} onClose={onClose} onConfirm={onConfirm} />;
    }
    if (r.action_kind === "video_edit") {
      // No modal — just confirm directly through a tiny dialog
      return <ConfirmExportBriefModal open={open} ad={ad} rec={r} onClose={onClose} onConfirm={onConfirm} />;
    }
    if (r.action_kind === "copy_overlay") {
      return <CopyOverlayModal open={open} ad={ad} rec={r} onClose={onClose} onConfirm={onConfirm} />;
    }
    // image_gen
    return <ImageGenModal open={open} ad={ad} recs={recs} onClose={onClose} onConfirm={onConfirm} />;
  }
  // Batch — present as image gen modal but warn about kind mix
  return <ImageGenModal open={open} ad={ad} recs={recs} onClose={onClose} onConfirm={onConfirm} batch />;
}

// ---------------- Image Gen modal (existing) ----------------
function ImageGenModal({ open, ad, recs, onClose, onConfirm, batch }) {
  const { Icon, Pill, Thumb } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const [urlState, setUrlState] = useState("ok");
  const [url, setUrl] = useState(window.BRAND.url);
  const [contextKind, setContextKind] = useState("brief");
  const [ratio, setRatio] = useState("2:3");
  const [batchSize, setBatchSize] = useState(4);
  const [selectedImages, setSelectedImages] = useState(new Set([0, 1]));
  const [style, setStyle] = useState("Editorial photography");
  const [generating, setGenerating] = useState(false);

  useEffect(() => {
    if (!open) { setUrlState("ok"); setGenerating(false); }
  }, [open]);

  const parseUrl = () => {
    setUrlState("loading");
    setTimeout(() => setUrlState(url.includes("fail") ? "error" : "ok"), 1200);
  };

  const handleGenerate = () => {
    setGenerating(true);
    setTimeout(() => onConfirm({ ratio, batchSize, style }), 400);
  };

  // Show kind breakdown when batched
  const kindCounts = recs.reduce((m, r) => (m[r.action_kind] = (m[r.action_kind] || 0) + 1, m), {});
  const totalImages = recs.filter(r => r.action_kind === "image_gen" || r.action_kind === "copy_overlay").length * batchSize;

  return (
    <div className={"modal-scrim open"} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 620 }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--rule)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div>
            <div className="label">{t("Step 2 of 2 · image gen", "第 2 步,共 2 步 · 出图")}</div>
            <div className="t-h1">{t("Ad context.", "广告上下文。")}</div>
          </div>
          <button className="btn ghost icon" onClick={onClose}><Icon name="close" /></button>
        </div>

        {/* What you're iterating */}
        <div style={{ padding: "12px 20px", background: "var(--bg-deep)", borderBottom: "1px solid var(--rule)" }}>
          <div className="label" style={{ marginBottom: 6 }}>{t("You're about to run", "即将运行")}</div>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <Thumb ad={ad} w={40} h={40} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="t-h3" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{isZh && ad.headlineZh ? ad.headlineZh : ad.headline}</div>
              <div style={{ display: "flex", gap: 4, flexWrap: "wrap", marginTop: 4 }}>
                {recs.map(r => <Pill key={r.id} variant="accent" style={{ fontSize: 9 }}>{isZh && r.titleZh ? r.titleZh : r.title}</Pill>)}
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div className="t-h1" style={{ fontSize: 26, lineHeight: 1 }}>{recs.length}</div>
              <div className="label">{t("moves", "动作")}</div>
            </div>
          </div>
          {batch && Object.keys(kindCounts).length > 1 && (
            <div style={{ marginTop: 10, padding: 10, background: "var(--card)", border: "1px solid var(--rule)", borderRadius: 4, fontSize: 11, color: "var(--ink-3)" }}>
              <strong style={{ color: "var(--ink)" }}>{t("Heads up · mixed kinds.", "注意 · 类型混合。")}</strong> {t("Targeting changes and brief exports skip this form; only image-gen moves use the settings below.", "调受众和导 brief 这两类会跳过这个表单;只有「出图」类型的动作会用下面的设置。")}
            </div>
          )}
        </div>

        <div style={{ padding: 20, display: "flex", flexDirection: "column", gap: 16, maxHeight: "55vh", overflow: "auto" }}>
          <Field label="Context">
            <Segmented options={["Brief", "Free text"]} value={contextKind === "brief" ? "Brief" : "Free text"} onChange={v => setContextKind(v === "Brief" ? "brief" : "text")} />
          </Field>

          <Field label="Product URL">
            <div style={{ display: "flex", gap: 6 }}>
              <input className="input" value={url} onChange={e => setUrl(e.target.value)} style={inputStyle()} placeholder="https://yourbrand.com/product" />
              <button className="btn sm" onClick={parseUrl} disabled={urlState === "loading"}>
                {urlState === "loading" ? <><span className="spinner" />Parsing…</> : "Generate"}
              </button>
            </div>
            {urlState === "error" && (
              <div style={{ marginTop: 8, padding: 10, background: "var(--card)", border: "1px solid var(--rule-strong)", borderRadius: 4, fontSize: 12 }}>
                <div style={{ display: "flex", gap: 6, alignItems: "center", color: "var(--grade-d)" }}>
                  <Icon name="warn" size={14} /><strong>We couldn't auto-parse this URL.</strong>
                </div>
                <div style={{ color: "var(--ink-3)", marginTop: 4 }}>Fill in the product details manually below, or paste a different URL.</div>
                <div style={{ marginTop: 8, display: "flex", gap: 8 }}>
                  <button className="btn sm" onClick={() => setUrlState("ok")}>Fill manually</button>
                  <button className="btn sm ghost" onClick={() => setUrlState("ok")}>Use brand defaults</button>
                </div>
              </div>
            )}
          </Field>

          {urlState === "ok" && (
            <div style={{ padding: 12, background: "var(--bg)", border: "1px solid var(--rule)", borderRadius: 4 }}>
              <div className="label" style={{ marginBottom: 6 }}>{t("Parsed · editable", "已解析 · 可编辑")}</div>
              <Field label={t("Product / Service name", "产品 / 服务名称")} tight>
                <input style={inputStyle()} defaultValue={window.BRAND.name} />
              </Field>
              <Field label={t("Description", "描述")} tight>
                <textarea rows={2} style={{ ...inputStyle(), resize: "vertical" }} defaultValue={window.BRAND.description} />
              </Field>
              <Field label={t("Product images", "产品图片")} tight>
                <div style={{ display: "flex", gap: 8 }}>
                  {window.BRAND.productImages.map((p, i) => (
                    <div key={i}
                      onClick={() => setSelectedImages(s => { const n = new Set(s); n.has(i) ? n.delete(i) : n.add(i); return n; })}
                      style={{ width: 56, height: 56, cursor: "pointer", outline: selectedImages.has(i) ? "2px solid var(--accent)" : "none", outlineOffset: 2 }}>
                      <Thumb ad={{ code: p, type: "image" }} w={56} h={56} />
                    </div>
                  ))}
                </div>
              </Field>
            </div>
          )}

          <Field label={t("Visual style", "视觉风格")}>
            <Segmented options={window.BRAND.styles} value={style} onChange={setStyle} compact />
          </Field>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <Field label={t("Aspect ratio", "画面比例")}>
              <Segmented options={["1:1", "4:5", "2:3", "9:16"]} value={ratio} onChange={setRatio} />
            </Field>
            <Field label={t(`Batch size · ${batchSize} per move`, `批量大小 · 每条建议出 ${batchSize} 张`)}>
              <input type="range" min="1" max="6" value={batchSize} onChange={e => setBatchSize(+e.target.value)} style={{ width: "100%" }} />
            </Field>
          </div>
        </div>

        <div style={{ padding: "14px 20px", borderTop: "1px solid var(--rule)", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ fontSize: 11, color: "var(--ink-3)" }}>
            ~ {Math.round(30 + recs.length * 8)}s · {totalImages} {t("images", "张图")}, {ratio}, {style.toLowerCase()}
          </div>
          <div style={{ flex: 1 }} />
          <button className="btn ghost" onClick={onClose}>{t("Cancel", "取消")}</button>
          <button className="btn primary" onClick={handleGenerate} disabled={generating}>
            {generating ? <><span className="spinner" />{t("Queuing…", "排队中…")}</> : <><Icon name="bolt" size={12} />{t(`Run ${recs.length} move${recs.length>1?"s":""}`, `运行 ${recs.length} 条建议`)}</>}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------- Targeting modal — one-step diff confirm ----------------
function TargetingModal({ open, ad, rec, onClose, onConfirm }) {
  const { Icon, Pill, MetricDelta } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const [applying, setApplying] = useState(false);

  const handle = () => {
    setApplying(true);
    setTimeout(() => onConfirm({ kind: "targeting_change" }), 600);
  };

  return (
    <div className="modal-scrim open" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 580 }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--rule)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div className="label">{t("Targeting update · Meta Ads Manager", "调整受众 · Meta 广告后台")}</div>
            <div className="t-h1">{t("Confirm the change.", "确认调整内容。")}</div>
          </div>
          <button className="btn ghost icon" onClick={onClose}><Icon name="close" /></button>
        </div>

        <div style={{ padding: 20 }}>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55, maxWidth: 480 }}>
            {isZh && rec.whyZh ? rec.whyZh : rec.why}
          </div>

          <div style={{ marginTop: 16, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <DiffCol title={t("Current", "现在")} rows={[
              [t("Age range", "年龄段"), "18-44"],
              [t("Geo", "地区"), t("US · all metros", "美国 · 全部都市")],
              [t("Lookalikes", "相似人群"), "—"],
              [t("Excluded", "排除人群"), "—"],
            ]} />
            <DiffCol title={t("Recommended", "推荐")} highlight rows={[
              [t("Age range", "年龄段"), "28-44"],
              [t("Geo", "地区"), t("US · top 50 metros", "美国 · 50 大都市")],
              [t("Lookalikes", "相似人群"), t("1% LAL · 30-day purchasers", "1% 相似 · 30 天内购买者")],
              [t("Excluded", "排除人群"), t("Existing customers", "现有客户")],
            ]} />
          </div>

          <div style={{ marginTop: 14, padding: 12, background: "var(--bg)", border: "1px solid var(--rule)", borderRadius: 4 }}>
            <div className="label" style={{ marginBottom: 6 }}>{t("Predicted impact", "预测效果")}</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <MetricDelta {...rec.primaryMetric} metricName={rec.primaryMetric.name} delta={rec.primaryMetric.delta} />
              <span style={{ fontSize: 11, color: "var(--ink-3)" }}>
                {t("Spend re-allocated immediately · effect visible within ~6 hours.", "预算立刻重新分配 · 效果约 6 小时后可见。")}
              </span>
            </div>
          </div>
        </div>

        <div style={{ padding: "14px 20px", borderTop: "1px solid var(--rule)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn ghost" onClick={onClose}>{t("Cancel", "取消")}</button>
          <button className="btn primary" onClick={handle} disabled={applying}>
            {applying ? <><span className="spinner" />{t("Syncing with Meta…", "同步到 Meta 中…")}</> : <><Icon name="check" size={12} />{t("Apply change", "应用调整")}</>}
          </button>
        </div>
      </div>
    </div>
  );
}

function DiffCol({ title, rows, highlight }) {
  return (
    <div style={{
      border: "1px solid " + (highlight ? "var(--accent-tint-2)" : "var(--rule)"),
      borderRadius: 4, padding: 12,
      background: highlight ? "var(--accent-tint)" : "var(--card)",
    }}>
      <div className="label" style={{ color: highlight ? "var(--accent)" : "var(--ink-3)", marginBottom: 8 }}>{title}</div>
      {rows.map(([k, v]) => (
        <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: "1px solid " + (highlight ? "var(--accent-tint-2)" : "var(--rule)"), fontSize: 11 }}>
          <span style={{ color: "var(--ink-3)" }}>{k}</span>
          <span className="mono" style={{ fontWeight: highlight ? 600 : 400, textAlign: "right" }}>{v}</span>
        </div>
      ))}
    </div>
  );
}

// ---------------- Copy Overlay modal — simpler form (no images, no ratio) ----------------
function CopyOverlayModal({ open, ad, rec, onClose, onConfirm }) {
  const { Icon, Pill, MetricDelta } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const [tone, setTone] = useState(t("Imperative", "命令式"));
  const [length, setLength] = useState(t("Short (≤8 words)", "短(≤8 词)"));
  const [generating, setGenerating] = useState(false);

  const handle = () => {
    setGenerating(true);
    setTimeout(() => onConfirm({ tone, length }), 400);
  };

  return (
    <div className="modal-scrim open" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 540 }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--rule)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div className="label">{t("Copy variants · text + overlay", "文案变体 · 文本 + 叠加")}</div>
            <div className="t-h1">{t("Copy direction.", "文案方向。")}</div>
          </div>
          <button className="btn ghost icon" onClick={onClose}><Icon name="close" /></button>
        </div>
        <div style={{ padding: 20, display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55 }}>{isZh && rec.whyZh ? rec.whyZh : rec.why}</div>
          <Field label={t("Tone", "语气")}>
            <Segmented options={[t("Imperative", "命令式"), t("Curious", "好奇式"), t("Bold", "大胆")]} value={tone} onChange={setTone} />
          </Field>
          <Field label={t("Length", "长度")}>
            <Segmented options={[t("Short (≤8 words)", "短(≤8 词)"), t("Medium (8-16)", "中(8-16)"), t("Long (16+)", "长(16+)")]} value={length} onChange={setLength} compact />
          </Field>
          <div style={{ padding: 12, background: "var(--bg)", border: "1px solid var(--rule)", borderRadius: 4 }}>
            <div className="label" style={{ marginBottom: 6 }}>{t("Predicted lift", "预测涨幅")}</div>
            <MetricDelta {...rec.primaryMetric} metricName={rec.primaryMetric.name} delta={rec.primaryMetric.delta} />
          </div>
        </div>
        <div style={{ padding: "14px 20px", borderTop: "1px solid var(--rule)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn ghost" onClick={onClose}>{t("Cancel", "取消")}</button>
          <button className="btn primary" onClick={handle} disabled={generating}>
            {generating ? <><span className="spinner" />{t("Queuing…", "排队中…")}</> : <><Icon name="bolt" size={12} />{t("Generate 4 copy variants", "生成 4 个文案变体")}</>}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------- Confirm export brief (tiny) ----------------
function ConfirmExportBriefModal({ open, ad, rec, onClose, onConfirm }) {
  const { Icon } = window;
  const t = window.useT();
  return (
    <div className="modal-scrim open" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 480 }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--rule)" }}>
          <div className="label">{t("Video brief export", "视频 brief 导出")}</div>
          <div className="t-h1">{t("Send to your editor.", "发给你的剪辑师。")}</div>
        </div>
        <div style={{ padding: 20 }}>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55 }}>
            {t(
              "We'll package this recommendation as a PDF brief — frame-by-frame guidance, timing notes, copy options — and drop it into your team's Notion / shared drive.",
              "我们会把这条建议打包成一份 PDF brief —— 逐帧指导、节奏提示、文案备选 —— 然后丢到你们团队的 Notion / 共享盘里。"
            )}
          </div>
        </div>
        <div style={{ padding: "14px 20px", borderTop: "1px solid var(--rule)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn ghost" onClick={onClose}>{t("Cancel", "取消")}</button>
          <button className="btn primary" onClick={() => onConfirm({ kind: "video_edit" })}>
            <Icon name="download" size={12} />{t("Export brief", "导出 brief")}
          </button>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children, tight }) {
  return (
    <div style={{ marginBottom: tight ? 10 : 0 }}>
      <div className="label" style={{ marginBottom: 6 }}>{label}</div>
      {children}
    </div>
  );
}

function Segmented({ options, value, onChange, compact }) {
  return (
    <div style={{ display: "inline-flex", border: "1px solid var(--rule-strong)", borderRadius: 4, overflow: "hidden", flexWrap: compact ? "wrap" : "nowrap" }}>
      {options.map(o => (
        <button key={o} onClick={() => onChange(o)}
          style={{
            padding: compact ? "5px 10px" : "6px 14px",
            fontSize: 11,
            background: o === value ? "var(--ink)" : "transparent",
            color: o === value ? "var(--bg)" : "var(--ink-2)",
            borderRight: "1px solid var(--rule)",
          }}>
          {o}
        </button>
      ))}
    </div>
  );
}

function inputStyle() {
  return {
    width: "100%",
    padding: "6px 10px",
    border: "1px solid var(--rule-strong)",
    borderRadius: 4,
    background: "var(--card)",
    fontSize: 12,
    fontFamily: "IBM Plex Mono, monospace",
  };
}

Object.assign(window, { ActionModal, AddContextModal: ActionModal });
