// dashboard-event-promotion-campaign-drawe.js — extracted verbatim from dashboard.js (pure move).

// ── Event promotion campaign drawer (v60) ────────────────────────
//
// Three sections:
//   1. Status header — current state + Start/Pause/Stop buttons
//   2. Setup section — TG groups picker (only meaningful pre-Start)
//   3. Approval queue — drafted rows with Approve / Edit / Skip
// All wired to the /api/crm/event-campaigns endpoints via the api proxy.
async function showEventCampaignDrawer(workflowId) {
  let activeStatus = "drafted"; // which audience-status to show in the queue

  async function load() {
    const qs = `?status=${encodeURIComponent(activeStatus)}&limit=50`;
    return await api("evc-detail", { id: workflowId, queryString: qs });
  }

  async function refresh() {
    const data = await load();
    if (data?.error) {
      toast(`Error: ${data.error}`, "err");
      return;
    }
    renderBody(data);
  }

  function renderBody(data) {
    const body = $("#drawer-body");
    if (!body) return;
    body.innerHTML = "";

    const wf = data.workflow;
    const config = (() => {
      try {
        return JSON.parse(wf.config_json || "{}");
      } catch {
        return {};
      }
    })();
    const counts = data.counts || {};
    const audience = data.audience || [];

    // ── Status header with action buttons ───────────────────────
    const status = wf.status || "configuring";
    const statusColors = {
      running: "var(--green)",
      paused: "var(--yellow)",
      completed: "var(--text-3)",
      configuring: "var(--text-2)",
    };
    body.appendChild(
      el("div", { style: "display:flex;align-items:center;gap:8px;margin-bottom:12px;" }, [
        el("span", {
          style: `width:8px;height:8px;border-radius:50%;background:${statusColors[status] || "var(--text-3)"};`,
        }),
        el(
          "div",
          {
            style:
              "flex:1;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;font-size:11px;color:var(--text-2);",
          },
          status,
        ),
        status !== "running"
          ? el(
              "button",
              {
                class: "btn btn-tiny btn-primary",
                type: "button",
                onclick: async () => {
                  const r = await api("evc-start", { id: wf.id });
                  if (r?.ok) {
                    toast(
                      "▶ Started — discovery + drafting will run on next cron tick",
                      "ok",
                      5000,
                    );
                    refresh();
                  } else toast(r?.error || "failed", "err");
                },
              },
              "▶ Start",
            )
          : null,
        status === "running"
          ? el(
              "button",
              {
                class: "btn btn-tiny btn-secondary",
                type: "button",
                onclick: async () => {
                  const r = await api("evc-pause", { id: wf.id });
                  if (r?.ok) {
                    toast("⏸ Paused", "ok");
                    refresh();
                  }
                },
              },
              "⏸ Pause",
            )
          : null,
        status !== "completed"
          ? el(
              "button",
              {
                class: "btn btn-tiny btn-danger",
                type: "button",
                onclick: async () => {
                  if (!confirm("Stop this campaign? Cannot be resumed.")) return;
                  const r = await api("evc-stop", { id: wf.id });
                  if (r?.ok) {
                    toast("Stopped", "ok");
                    refresh();
                  }
                },
              },
              "■ Stop",
            )
          : null,
      ]),
    );

    // Counts header
    const countsRow = el("div", {
      class: "row",
      style: "gap:6px;flex-wrap:wrap;margin-bottom:14px;font-size:11px;",
    });
    const PILL = (label, n, color) =>
      el(
        "span",
        {
          style: `padding:3px 8px;background:var(--bg-2);border:1px solid ${color}33;color:${color};border-radius:var(--radius-full);font-weight:600;`,
        },
        `${label} ${n || 0}`,
      );
    countsRow.appendChild(PILL("queued", counts.queued, "var(--text-3)"));
    countsRow.appendChild(PILL("drafted", counts.drafted, "var(--accent)"));
    countsRow.appendChild(PILL("approved", counts.approved, "var(--blue)"));
    countsRow.appendChild(PILL("sent", counts.sent, "var(--green)"));
    if (counts.cooled) countsRow.appendChild(PILL("cooled", counts.cooled, "var(--yellow)"));
    if (counts.skipped) countsRow.appendChild(PILL("skipped", counts.skipped, "var(--text-4)"));
    if (counts.failed) countsRow.appendChild(PILL("failed", counts.failed, "var(--red)"));
    body.appendChild(countsRow);

    // ── Event details
    body.appendChild(el("h4", {}, "Event"));
    body.appendChild(
      el(
        "div",
        { class: "muted small", style: "line-height:1.6;margin-bottom:14px;" },
        [
          `${config.eventName || wf.name}${config.location ? ` · ${config.location}` : ""}`,
          config.audience ? el("div", {}, `Audience: ${config.audience}`) : null,
          config.ticketLink
            ? el("div", {}, [
                "Link: ",
                el(
                  "a",
                  { href: config.ticketLink, target: "_blank", style: "color:var(--accent);" },
                  config.ticketLink,
                ),
              ])
            : null,
        ].filter(Boolean),
      ),
    );

    // ── Telegram groups picker (only meaningful when not yet running)
    if (status === "configuring" || status === "paused") {
      body.appendChild(el("h4", {}, "Telegram groups (handpicked)"));
      body.appendChild(
        el(
          "div",
          { class: "muted small", style: "margin-bottom:8px;" },
          "Paste invite links one per line, or chat_ids of already-joined groups.",
        ),
      );
      const inviteInput = el("textarea", {
        class: "wizard-textarea",
        rows: "3",
        placeholder:
          "https://t.me/eth_global_chat\nhttps://t.me/joinchat/AAAAAFakeInviteHash\n-1001234567890   (chat_id of an already-joined group)",
        style: "width:100%;",
      });
      body.appendChild(inviteInput);
      body.appendChild(
        el(
          "button",
          {
            class: "btn btn-tiny btn-primary",
            type: "button",
            style: "margin-top:6px;",
            onclick: async () => {
              const lines = inviteInput.value
                .split(/\n/)
                .map((s) => s.trim())
                .filter(Boolean);
              const chatIds = lines.filter((l) => /^-?\d+$/.test(l));
              const inviteLinks = lines.filter((l) => !/^-?\d+$/.test(l));
              const r = await api("evc-tg-groups", { id: wf.id, body: { chatIds, inviteLinks } });
              if (r?.ok) {
                toast(`Added ${r.added} group(s)`, "ok");
                inviteInput.value = "";
                refresh();
              } else toast(r?.error || "failed", "err");
            },
          },
          "+ Add groups",
        ),
      );
    }

    // ── Approval queue
    body.appendChild(el("h4", { style: "margin-top:16px;" }, "Approval queue"));
    // Sub-tabs to switch which audience-status the queue shows.
    const subtabs = el("div", { class: "tabs", style: "margin-bottom:8px;font-size:11px;" });
    for (const s of ["drafted", "approved", "sent", "queued", "cooled", "skipped"]) {
      subtabs.appendChild(
        el(
          "button",
          {
            class: `tab${activeStatus === s ? " active" : ""}`,
            type: "button",
            onclick: () => {
              activeStatus = s;
              refresh();
            },
          },
          `${s} ${counts[s] || 0}`,
        ),
      );
    }
    body.appendChild(subtabs);

    if (audience.length === 0) {
      body.appendChild(
        el(
          "div",
          { class: "muted small", style: "padding:12px;text-align:center;" },
          activeStatus === "drafted"
            ? "No drafts yet. After Start, drafts appear within ~30 min."
            : `No ${activeStatus} rows.`,
        ),
      );
    } else {
      // "Approve all visible" header for drafted rows
      if (activeStatus === "drafted") {
        body.appendChild(
          el(
            "button",
            {
              class: "btn btn-tiny btn-primary",
              type: "button",
              style: "margin-bottom:10px;",
              onclick: async () => {
                const ids = audience.map((a) => a.id);
                const r = await api("evc-approve", { body: { ids } });
                if (r?.ok) {
                  toast(`Approved ${r.updated} drafts`, "ok");
                  refresh();
                }
              },
            },
            `Approve all ${audience.length} visible`,
          ),
        );
      }

      for (const row of audience) {
        const kindIcon =
          row.target_kind === "tw_user" ? "🐦" : row.target_kind === "li_user" ? "🔗" : "✈";
        const target =
          row.target_handle || row.target_chat_id || row.target_invite_link || "(unknown)";

        const card = el("div", {
          style:
            "border:1px solid var(--border);background:var(--bg-2);border-radius:var(--radius-md);padding:10px 12px;margin-bottom:8px;",
        });
        card.appendChild(
          el(
            "div",
            { class: "row", style: "gap:6px;align-items:center;margin-bottom:6px;font-size:11px;" },
            [
              el("span", { style: "font-size:13px;" }, kindIcon),
              el(
                "span",
                {
                  style:
                    "font-weight:600;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;",
                },
                target,
              ),
              row.source_handle
                ? el("span", { class: "muted small mono" }, `via ${row.source_handle}`)
                : null,
            ],
          ),
        );

        if (row.ai_drafted_message) {
          // Editable message textarea — operator can override the AI draft
          // before approving. Saves on blur via /audience/edit.
          const msgArea = el(
            "textarea",
            {
              class: "wizard-textarea",
              rows: row.target_kind === "tg_group" ? "3" : "2",
              style: "width:100%;font-size:12px;line-height:1.5;",
              onblur: async (e) => {
                const newText = e.target.value.trim();
                if (newText === row.ai_drafted_message) return;
                const r = await api("evc-edit", { body: { id: row.id, message: newText } });
                if (r?.ok) {
                  toast("Draft saved", "ok", 1500);
                  row.ai_drafted_message = newText;
                }
              },
            },
            row.ai_drafted_message,
          );
          card.appendChild(msgArea);
        }

        if (row.last_error) {
          card.appendChild(
            el(
              "div",
              {
                class: "muted small",
                style:
                  "color:var(--red);font-family:var(--font-mono);font-size:10px;margin-top:4px;",
              },
              row.last_error,
            ),
          );
        }

        // Action buttons (only meaningful for drafted rows)
        if (row.status === "drafted") {
          card.appendChild(
            el("div", { class: "row", style: "gap:6px;margin-top:6px;" }, [
              el(
                "button",
                {
                  class: "btn btn-tiny btn-primary",
                  type: "button",
                  onclick: async () => {
                    const r = await api("evc-approve", { body: { ids: [row.id] } });
                    if (r?.ok) {
                      toast("Approved", "ok", 1500);
                      refresh();
                    }
                  },
                },
                "Approve",
              ),
              el(
                "button",
                {
                  class: "btn btn-tiny btn-secondary",
                  type: "button",
                  onclick: async () => {
                    const r = await api("evc-skip", { body: { ids: [row.id] } });
                    if (r?.ok) {
                      toast("Skipped", "ok", 1500);
                      refresh();
                    }
                  },
                },
                "Skip",
              ),
            ]),
          );
        }

        // Footer metadata
        const meta = [];
        if (row.drafted_at) meta.push(`drafted ${fmtDate(row.drafted_at)}`);
        if (row.approved_at) meta.push(`approved ${fmtDate(row.approved_at)}`);
        if (row.sent_at) meta.push(`sent ${fmtDate(row.sent_at)}`);
        if (row.action_count > 1) meta.push(`×${row.action_count}`);
        if (meta.length > 0) {
          card.appendChild(
            el(
              "div",
              { class: "muted small mono", style: "font-size:10px;margin-top:4px;" },
              meta.join(" · "),
            ),
          );
        }

        body.appendChild(card);
      }
    }
  }

  // Open the drawer empty, then load.
  openDrawer("Event campaign", el("div", { class: "muted small" }, "Loading…"));
  refresh();
}

// Route page for #hiring-review — a thin landing that explains the queue and
// opens the review drawer (the drawer holds the actual list + actions).
async function renderHiringReview() {
  const wrap = el("div", { style: "padding:16px;max-width:720px;" });
  setContentNode(wrap);
  wrap.appendChild(
    el("div", { class: "page-header", style: "margin-bottom:10px;" }, [
      el("h1", { style: "margin:0;font-size:18px;" }, "Hiring Outreach — review"),
      el(
        "p",
        { class: "muted", style: "margin:4px 0 0;font-size:12px;line-height:1.5;" },
        "The Crypto Hiring Outreach automation finds companies hiring for roles your services fit, then AI-drafts a LinkedIn comment for the company page and the latest post of a director/rep. Review and approve each comment before it posts publicly.",
      ),
    ]),
  );
  wrap.appendChild(
    el(
      "button",
      {
        class: "btn btn-primary",
        style: "margin-top:8px;",
        onclick: () => showHiringOutreachDrawer(),
      },
      "Open review queue →",
    ),
  );
  // Live counts strip so the page isn't empty before they open the drawer.
  const strip = el("div", { class: "muted small", style: "margin-top:14px;" }, "Loading counts…");
  wrap.appendChild(strip);
  try {
    const data = await api("lic-list", { queryString: "?status=drafted&limit=1" });
    const c = data?.counts || {};
    strip.textContent = `${c.drafted || 0} awaiting review · ${c.approved || 0} approved · ${c.sent || 0} sent`;
  } catch {
    strip.textContent = "";
  }
  // Auto-open the drawer for the common case (they came here to review).
  showHiringOutreachDrawer();
}
