/* global React, window */
// Tasks dropdown panel.

const { useState } = React;

function TasksPanel({ open, tasks, onClose, onOpenTask, ads }) {
  const { Icon, Pill, Thumb, relTime } = window;
  const tt = window.useT();
  const [tab, setTab] = useState("all");

  const filtered = tasks.filter(t => tab === "all" ? true : t.status === tab);
  const counts = {
    running: tasks.filter(t => t.status === "running").length,
    completed: tasks.filter(t => t.status === "completed").length,
    failed: tasks.filter(t => t.status === "failed").length,
    all: tasks.length,
  };

  const tabLabelMap = {
    running: tt("Running", "进行中"),
    completed: tt("Completed", "已完成"),
    failed: tt("Failed", "失败"),
    all: tt("All", "全部"),
  };

  if (!open) return null;

  return (
    <div className={"tasks-pop " + (open ? "open" : "")}>
      <div style={{ padding: "12px 16px", display: "flex", alignItems: "center", borderBottom: "1px solid var(--rule)" }}>
        <div className="t-h2">{tt("Tasks", "任务")}</div>
        <div style={{ flex: 1 }} />
        <button className="btn ghost icon" onClick={onClose}><Icon name="close" size={14} /></button>
      </div>
      <div style={{ display: "flex", padding: "0 8px", borderBottom: "1px solid var(--rule)" }}>
        {[
          { id: "running", label: tt("Running", "进行中") },
          { id: "completed", label: tt("Completed", "已完成") },
          { id: "failed", label: tt("Failed", "失败") },
          { id: "all", label: tt("All", "全部") },
        ].map(opt => (
          <div key={opt.id} className={"tab " + (tab === opt.id ? "active" : "")} onClick={() => setTab(opt.id)} style={{ padding: "9px 10px", fontSize: 11 }}>
            <span>{opt.label}</span>
            <span className="tab-count">{counts[opt.id]}</span>
          </div>
        ))}
      </div>

      <div style={{ padding: 8, display: "flex", flexDirection: "column", gap: 6 }}>
        {filtered.length === 0 && (
          <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>{tt("No", "暂无")} {tabLabelMap[tab]} {tt("tasks.", "任务。")}</div>
        )}
        {filtered.map(t => {
          const ad = ads.find(a => a.id === t.adId);
          const isClickable = t.status === "completed";
          const kindLabel = t.action_kind === "copy_overlay" ? tt("Copy", "文案") : t.action_kind === "targeting_change" ? tt("Targeting", "受众") : t.action_kind === "video_edit" ? tt("Brief", "剪辑 brief") : tt("Image", "图片");
          return (
            <div key={t.id}
              onClick={() => isClickable && onOpenTask(t)}
              style={{
                padding: 10, border: "1px solid var(--rule)", borderRadius: 4, background: "var(--card)",
                display: "flex", gap: 10,
                cursor: isClickable ? "pointer" : "default",
                transition: "background .12s",
              }}
              onMouseEnter={e => { if (isClickable) e.currentTarget.style.background = "var(--bg-deep)"; }}
              onMouseLeave={e => { e.currentTarget.style.background = "var(--card)"; }}>
              <Thumb ad={ad} w={42} h={42} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{ad?.code}</span>
                  <span className="mono" style={{ fontSize: 9, padding: "0 4px", background: "var(--bg-deep)", color: "var(--ink-2)", borderRadius: 2 }}>{kindLabel}</span>
                </div>
                <div className="t-h3" style={{ fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                  {window.localizedRecTitle(t)}
                </div>
                {t.status === "running" && (
                  <>
                    <div className="progress" style={{ marginTop: 6 }}>
                      <span style={{ width: t.progress + "%" }} />
                    </div>
                    <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 3 }}>
                      {t.progress}% · {tt(`${t.eta}s remaining`, `还剩 ${t.eta} 秒`)}
                    </div>
                  </>
                )}
                {t.status === "completed" && (
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 3 }}>
                    {tt(`Completed ${relTime(t.completedAt)} · 4 variants ready`, `${relTime(t.completedAt)}完成 · 4 个变体待查看`)}
                  </div>
                )}
                {t.status === "failed" && (
                  <div style={{ fontSize: 10, color: "var(--grade-d)", marginTop: 3 }}>
                    {t.reason}
                  </div>
                )}
                <div className="mono" style={{ fontSize: 9, color: "var(--ink-4)", marginTop: 4 }}>
                  ← {tt("From Radar", "来自 Radar")} · {ad?.code}
                </div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
                {t.status === "running" && (
                  <div style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 10, color: "var(--status-running)", fontFamily: "IBM Plex Mono, monospace" }}>
                    <span className="spinner" style={{ width: 10, height: 10 }} />
                    {tt("Running", "运行中")}
                  </div>
                )}
                {t.status === "completed" && (
                  <Icon name="arrow" size={12} />
                )}
                {t.status === "failed" && (
                  <button className="btn sm" onClick={e => e.stopPropagation()}>
                    <Icon name="refresh" size={11} />{tt("Retry", "重试")}
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { TasksPanel });
