// dashboard-client-campaigns.js — classic script, shared global scope.
// Per-client campaign console: pick a customer, see everything running for them.
//
// Why this exists: campaigns were reachable only as one undifferentiated list of
// 69, with no way to answer "what are we running for this customer?". The data
// model already supported it (workflow_compositions.client_id, and /api/clients
// has always reported campaignCount) — nothing populated or surfaced it.
//
// Reuses the existing composition endpoints rather than adding new ones:
//   compositions-list  ?clientId=   the client's campaigns
//   composition-activate / -pause   the run/stop toggle
//   composition-funnel               per-campaign stats

const CLIENT_STATUS_ORDER = { active: 0, paused: 1, draft: 2, archived: 3 };

const CC_STATUS_TINT = {
  active: "background:#064e3b;color:#6ee7b7;",
  paused: "background:#422006;color:#fcd34d;",
  draft: "",
  archived: "",
};

function _ccStatusPill(status) {
  return el("span", { class: "pill", style: CC_STATUS_TINT[status] || "" }, status);
}

/** One campaign row: name, status, toggle, and a link into its detail/stats. */
function _ccCampaignRow(comp, onChanged) {
  const isActive = comp.status === "active";
  const toggle = el(
    "button",
    {
      class: `btn btn-tiny ${isActive ? "btn-secondary" : "btn-primary"}`,
      onclick: async () => {
        toggle.disabled = true;
        try {
          // Both routes take the id in the PATH, not a body — see
          // dashboard-routes.js `/api/compositions/:id/{activate,pause}`.
          await apiMutate(isActive ? "composition-pause" : "composition-activate", {
            id: comp.id,
          });
          await onChanged();
        } finally {
          toggle.disabled = false;
        }
      },
    },
    isActive ? "Pause" : "Run",
  );

  return el("tr", {}, [
    el(
      "td",
      {},
      [
        el(
          "a",
          {
            href: "#",
            onclick: (e) => {
              e.preventDefault();
              navigate(`workflows/detail/${comp.id}`);
            },
          },
          comp.name || `Campaign #${comp.id}`,
        ),
        comp.description
          ? el(
              "div",
              { class: "muted", style: "font-size:11px;" },
              String(comp.description).slice(0, 120),
            )
          : null,
      ].filter(Boolean),
    ),
    el("td", {}, _ccStatusPill(comp.status)),
    el("td", { class: "muted", style: "font-size:11px;" }, comp.updated_at || ""),
    el("td", {}, toggle),
  ]);
}

/** Group campaigns by status so "what's live" is answerable at a glance. */
function _ccGroup(comps, onChanged) {
  const sorted = [...comps].sort(
    (a, b) =>
      (CLIENT_STATUS_ORDER[a.status] ?? 9) - (CLIENT_STATUS_ORDER[b.status] ?? 9) ||
      String(a.name || "").localeCompare(String(b.name || "")),
  );
  return el("table", { class: "table" }, [
    el(
      "thead",
      {},
      el(
        "tr",
        {},
        ["Campaign", "Status", "Updated", ""].map((h) => el("th", {}, h)),
      ),
    ),
    el(
      "tbody",
      {},
      sorted.map((c) => _ccCampaignRow(c, onChanged)),
    ),
  ]);
}

async function renderClientDetail({ id } = {}) {
  const root = el("div", {});
  if (!id) {
    root.appendChild(el("div", { class: "muted" }, "No client selected."));
    return root;
  }

  const load = async () => {
    const [clientsRes, compsRes] = await Promise.all([
      api("clients-list").catch((e) => ({ error: e?.message })),
      api("compositions-list", { queryString: `?clientId=${encodeURIComponent(id)}` }).catch(
        (e) => ({ error: e?.message }),
      ),
    ]);
    return { clientsRes, compsRes };
  };

  const paint = async () => {
    const { clientsRes, compsRes } = await load();
    root.replaceChildren();

    if (clientsRes.error) {
      root.appendChild(showError(clientsRes.error, () => navigate(`clients/${id}`)));
      return;
    }
    const client = (clientsRes.clients || []).find((c) => c.id === id);
    if (!client) {
      root.appendChild(el("div", { class: "muted" }, "Client not found."));
      return;
    }

    root.appendChild(
      el("div", { class: "row", style: "align-items:center;gap:8px;" }, [
        el(
          "button",
          { class: "btn btn-secondary btn-tiny", onclick: () => navigate("clients") },
          "← Clients",
        ),
        el("h2", { style: "margin:0;" }, client.name),
      ]),
    );

    if (compsRes.error) {
      root.appendChild(showError(compsRes.error, paint));
      return;
    }

    const comps = compsRes.compositions || [];
    const counts = comps.reduce((acc, c) => {
      acc[c.status] = (acc[c.status] || 0) + 1;
      return acc;
    }, {});

    root.appendChild(
      el("div", { class: "row", style: "gap:6px;flex-wrap:wrap;margin:8px 0;" }, [
        el(
          "span",
          { class: "pill", style: CC_STATUS_TINT.active },
          `${counts.active || 0} running`,
        ),
        el("span", { class: "pill", style: CC_STATUS_TINT.paused }, `${counts.paused || 0} paused`),
        el("span", { class: "pill" }, `${counts.draft || 0} draft`),
      ]),
    );

    if (comps.length === 0) {
      root.appendChild(
        el("div", { class: "card" }, [
          el("div", { class: "card-title" }, "No campaigns yet"),
          el(
            "div",
            { class: "muted" },
            "Nothing is attributed to this client. Build one in the Operations Center, or assign an existing campaign here.",
          ),
        ]),
      );
      return;
    }

    root.appendChild(
      el("div", { class: "card" }, [
        el("div", { class: "card-title" }, "Campaigns for this client"),
        el("div", { style: "overflow-x:auto;" }, _ccGroup(comps, paint)),
      ]),
    );
  };

  await paint();
  return root;
}
