// dashboard-workflow-mission-control.js — extracted verbatim from dashboard.js (pure move).

// ── Workflow Mission Control ────────────────────────────────────
//
// The post-create landing page for any workflow (new_token_outreach,
// hiring_outreach, comment_campaign, etc.) Answers four questions in one view:
//   1. What IS this campaign?      → explainer card with steps + schedule
//   2. What's it doing right now?  → status pill + next-action banner
//   3. What's actually happening?  → activity sparkline + recent events table
//   4. How do I control it?        → pause/resume/run-now/delete buttons
//
// Auto-refreshes every 10s while the route is active and the tab is visible.

let _workflowControlTimer = null;

async function renderWorkflowControl(params) {
  const workflowId = params?.workflowId;
  if (!workflowId) return navigate("campaigns");

  // Stop any prior auto-refresh on remount.
  if (_workflowControlTimer) {
    clearInterval(_workflowControlTimer);
    _workflowControlTimer = null;
  }

  await _renderWorkflowControlOnce(workflowId);

  // Auto-refresh every 10s, paused when the tab is hidden.
  _workflowControlTimer = setInterval(() => {
    if (document.hidden) return;
    if (dashboardState.currentRoute !== "workflow/control") {
      clearInterval(_workflowControlTimer);
      _workflowControlTimer = null;
      return;
    }
    _renderWorkflowControlOnce(workflowId).catch(() => {});
  }, 10_000);
}

async function _renderWorkflowControlOnce(workflowId) {
  let data;
  try {
    data = await api("workflow-control", { workflowId });
  } catch (err) {
    // Most common cause: chrome extension service worker hasn't been reloaded
    // since this route was added. Show a clear, actionable message instead of
    // the generic "Render error" page.
    const isPortClosed = /message port closed/i.test(err.message || "");
    setContentNode(
      el("div", { class: "empty-state" }, [
        el("div", { class: "empty-state-icon" }, "🔄"),
        el(
          "div",
          { class: "empty-state-title" },
          isPortClosed ? "Extension needs reload" : "Couldn't load workflow",
        ),
        el(
          "div",
          { class: "empty-state-hint" },
          isPortClosed
            ? "The chrome extension is running an older background script that doesn't recognise this route. Open chrome://extensions and click ↻ to reload Nexus Connect — your workflow was created and saved."
            : `Error: ${err.message}`,
        ),
        el("div", { style: "display:flex;gap:8px;justify-content:center;margin-top:16px;" }, [
          el(
            "button",
            { class: "btn btn-primary", onclick: () => location.reload() },
            "↻ Reload dashboard",
          ),
          el(
            "button",
            { class: "btn btn-secondary", onclick: () => navigate("campaigns") },
            "« All campaigns",
          ),
        ]),
      ]),
    );
    return;
  }
  if (data?.error) {
    showError(data.error, () => navigate(`workflow/${workflowId}`));
    return;
  }

  const {
    workflow,
    explainer,
    config,
    stats,
    nextAction,
    activity,
    spawnedCampaigns,
    recentEvents,
    controls,
  } = data;

  const isActive = workflow.status === "active";
  const isPaused = workflow.status === "paused";
  const statusPill = isActive ? "badge-green" : isPaused ? "badge-yellow" : "badge-gray";

  const TYPE_ICONS = {
    service_outreach: "🎯",
    hiring_outreach: "💼",
    competitor_targeting: "🕵️",
    geo_outreach: "🌍",
    new_token_outreach: "🚀",
    comment_campaign: "💬",
    group_amplification: "📢",
    content_amplification: "📣",
    crm_campaign: "🗂",
    event_promotion: "🎉",
  };
  const icon = TYPE_ICONS[workflow.type] || "⚡";

  // ── Action helpers (use apiMutate for cache-busting writes)
  async function doToggle(enabled) {
    const r = await apiMutate("workflow-toggle", { workflowId, body: { enabled } });
    if (r?.ok) {
      toast(enabled ? "Resumed" : "Paused", "ok");
      _renderWorkflowControlOnce(workflowId);
    } else toast(`Error: ${r?.error || "failed"}`, "err");
  }
  async function doRunNow() {
    const __pv = await runWithPreview("campaign_workflow", workflowId, {});
    if (!__pv?.confirmed) return;
    const r = await api("workflow-run-now", { workflowId });
    if (r?.ok) {
      toast(`▶ ${r.engine || "engine"} started`, "ok");
      setTimeout(() => _renderWorkflowControlOnce(workflowId), 2000);
    } else toast(`❌ ${r?.error || "failed"}`, "err");
  }
  async function doDelete() {
    if (!confirm("Delete this workflow? This cannot be undone.")) return;
    const r = await apiMutate("workflow-delete", { workflowId });
    if (r?.ok) {
      toast("Deleted", "ok");
      navigate("campaigns");
    } else toast(`Error: ${r?.error || "failed"}`, "err");
  }

  // ── Sections
  const explainerCard = el("div", { class: "card" }, [
    el("div", { class: "card-title" }, "What this campaign does"),
    el(
      "div",
      { style: "font-size:13px;line-height:1.6;color:var(--text-2);" },
      explainer.description,
    ),
    explainer.steps?.length
      ? el("div", { style: "margin-top:12px;" }, [
          el("div", { class: "muted small", style: "margin-bottom:6px;" }, "Step flow"),
          el(
            "div",
            { style: "display:flex;flex-wrap:wrap;gap:6px;" },
            explainer.steps.map((s, i) =>
              el(
                "div",
                {
                  style:
                    "padding:5px 9px;background:var(--bg-2);border-radius:14px;font-size:11px;display:flex;gap:6px;align-items:center;",
                },
                [
                  el("span", { class: "muted mono", style: "font-size:9px;" }, String(i + 1)),
                  el("span", {}, s),
                ],
              ),
            ),
          ),
        ])
      : null,
    explainer.schedule
      ? el(
          "div",
          { class: "muted small", style: "margin-top:10px;" },
          `🕐 Schedule: ${explainer.schedule}`,
        )
      : null,
    !explainer.engineSupported
      ? el(
          "div",
          {
            class: "alert-card warning",
            style: "margin-top:12px;padding:8px 12px;font-size:12px;",
          },
          explainer.composerTemplate
            ? [
                // Phase O: redirect to composer template instead of dead-end warning.
                el("strong", {}, "ℹ Superseded by the Workflow Composer. "),
                el(
                  "span",
                  {},
                  `This legacy workflow type was replaced by composer template "${explainer.composerTemplate}". `,
                ),
                el(
                  "button",
                  {
                    class: "btn btn-tiny btn-primary",
                    style: "margin-left: 6px;",
                    type: "button",
                    onclick: () => _openTemplatesPickerModal(null, "all"),
                  },
                  `Open templates →`,
                ),
              ]
            : [
                el("strong", {}, "⚠ Engine not yet implemented. "),
                el(
                  "span",
                  {},
                  "This campaign type is configured but won't auto-execute. The configuration is saved and will work once the engine ships.",
                ),
              ],
        )
      : null,
  ]);

  const configEntries = Object.entries(config || {}).filter(([k]) => !k.startsWith("_"));
  const configCard = configEntries.length
    ? el("div", { class: "card" }, [
        el("div", { class: "card-title" }, "Your configuration"),
        el(
          "div",
          { style: "display:grid;grid-template-columns:auto 1fr;gap:6px 14px;font-size:12px;" },
          configEntries.flatMap(([k, v]) => [
            el(
              "div",
              { class: "muted", style: "text-transform:capitalize;" },
              k.replace(/([A-Z])/g, " $1").toLowerCase(),
            ),
            el(
              "div",
              { class: "mono", style: "word-break:break-word;" },
              typeof v === "string" && v.length > 200 ? v.slice(0, 200) + "…" : String(v ?? "—"),
            ),
          ]),
        ),
      ])
    : null;

  const statsCard = el("div", { class: "stats-grid" }, [
    statCard("Targets found", fmtNum(stats.targetsFound || 0)),
    statCard("Spawned campaigns", fmtNum(stats.campaignsCreated || spawnedCampaigns?.length || 0)),
    statCard("Active children", fmtNum(stats.spawnedActive || 0)),
    statCard("Events (recent)", fmtNum(stats.eventsTotal || 0)),
  ]);

  const activityCard = el("div", { class: "card" }, [
    _activitySparkline(activity || [], { width: 720, height: 64 }),
  ]);

  const spawnedCard =
    (spawnedCampaigns?.length || 0) === 0
      ? null
      : el("div", { class: "card" }, [
          el("div", { class: "card-title" }, `Spawned campaigns (${spawnedCampaigns.length})`),
          el("table", { class: "table" }, [
            el("thead", {}, [
              el("tr", {}, [
                el("th", {}, "Contact"),
                el("th", {}, "Status"),
                el("th", {}, "Events"),
                el("th", {}, "Created"),
                el("th", {}, ""),
              ]),
            ]),
            el(
              "tbody",
              {},
              spawnedCampaigns.slice(0, 25).map((sc) =>
                el(
                  "tr",
                  {
                    style: "cursor:pointer;",
                    onclick: () => navigate(`campaigns/outreach/${sc.id}`),
                  },
                  [
                    el("td", {}, [el("span", { class: "primary-cell" }, sc.name)]),
                    el("td", {}, [statusDot(sc.status)]),
                    el("td", { class: "mono" }, String(sc.event_count || 0)),
                    el("td", { class: "secondary-cell" }, fmtDate(sc.created_at)),
                    el("td", { class: "muted small" }, "→ detail"),
                  ],
                ),
              ),
            ),
          ]),
        ]);

  const eventsCard =
    (recentEvents?.length || 0) === 0
      ? el("div", { class: "card" }, [
          el("div", { class: "card-title" }, "Live actions"),
          el(
            "div",
            { class: "muted small" },
            "No events yet. Trigger Run-Now or wait for the scheduler.",
          ),
        ])
      : el("div", { class: "card" }, [
          el("div", { class: "card-title" }, `Live actions (${recentEvents.length})`),
          el("table", { class: "table" }, [
            el(
              "tbody",
              {},
              recentEvents.slice(0, 30).map((ev) =>
                el("tr", {}, [
                  el("td", {}, [
                    el(
                      "span",
                      { style: "font-size:14px;" },
                      { x: "🐦", twitter: "🐦", linkedin: "🔗", telegram: "✈️", email: "✉️" }[
                        ev.platform
                      ] || "•",
                    ),
                  ]),
                  el("td", { class: "primary-cell" }, ev.contact_name || "—"),
                  el("td", {}, [
                    el("span", { class: "badge " + statusClass(ev.event_type) }, ev.event_type),
                  ]),
                  el(
                    "td",
                    {
                      class: "muted small",
                      style:
                        "max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;",
                    },
                    (ev.detail || "").slice(0, 100),
                  ),
                  el("td", { class: "secondary-cell" }, fmtDate(ev.created_at)),
                ]),
              ),
            ),
          ]),
        ]);

  const content = el("div", {}, [
    el("div", { class: "page-header" }, [
      el("div", {}, [
        el(
          "button",
          { class: "btn btn-secondary btn-tiny", onclick: () => navigate("campaigns") },
          "« All campaigns",
        ),
        el(
          "div",
          {
            class: "page-title",
            style: "margin-top:10px;display:flex;align-items:center;gap:10px;",
          },
          [
            el("span", { style: "font-size:24px;" }, icon),
            el("span", {}, workflow.name || `Workflow #${workflow.id}`),
            el("span", { class: `badge ${statusPill}` }, workflow.status),
          ],
        ),
        el(
          "div",
          { class: "page-subtitle" },
          `${workflow.type.replace(/_/g, " ")} · created ${fmtDate(workflow.createdAt)}`,
        ),
      ]),
      el("div", { style: "display:flex;gap:6px;flex-wrap:wrap;" }, [
        controls.canRunNow
          ? el(
              "button",
              {
                class: "btn btn-primary",
                onclick: doRunNow,
                title: "Trigger this workflow's engine immediately",
              },
              "⚡ Run now",
            )
          : null,
        controls.canPause
          ? el("button", { class: "btn btn-secondary", onclick: () => doToggle(false) }, "⏸ Pause")
          : null,
        controls.canResume
          ? el("button", { class: "btn btn-primary", onclick: () => doToggle(true) }, "▶ Resume")
          : null,
        el(
          "button",
          { class: "btn btn-secondary", onclick: () => _renderWorkflowControlOnce(workflowId) },
          "↻ Refresh",
        ),
        controls.canDelete
          ? el("button", { class: "btn btn-danger", onclick: doDelete }, "🗑 Delete")
          : null,
      ]),
    ]),

    // Next-action banner
    nextAction
      ? el(
          "div",
          {
            class: "card",
            style:
              "padding:10px 14px;border-left:3px solid " +
              (isActive ? "#5fb37c" : isPaused ? "#e8a317" : "#999") +
              ";font-size:13px;display:flex;align-items:center;gap:8px;",
          },
          [
            el("span", { style: "font-size:16px;" }, isActive ? "🤖" : isPaused ? "⏸" : "⚙"),
            el("span", {}, nextAction),
          ],
        )
      : null,

    explainerCard,
    configCard,
    statsCard,
    activityCard,
    spawnedCard,
    eventsCard,
  ]);
  setContentNode(content);
}
