// dashboard-campaign-detail-visual-breakdo.js — extracted verbatim from dashboard.js (pure move).

// ── Campaign detail (visual breakdown) ──────────────────────────────
//
// One renderer for all three campaign types (dm / email / outreach).
// Layout:
//   [back] [title + status pill] [pause/resume buttons]
//   [funnel cards / stat cards]
//   [activity sparkline (last 7 days)]
//   [next-action banner — what is the bot about to do]
//   [outreach: per-channel breakdown card]
//   [outreach: inbound notifications received from this contact]
//   [recent events table]

function _activitySparkline(buckets, opts = {}) {
  const width = opts.width || 360;
  const height = opts.height || 56;
  const pad = 4;
  if (!buckets || buckets.length === 0) {
    return el(
      "div",
      {
        class: "muted small",
        style: `width:${width}px;height:${height}px;display:flex;align-items:center;justify-content:center;`,
      },
      "no activity",
    );
  }
  // Bucket into 7×24 = 168 hour grid. Fill missing hours with 0.
  const now = new Date();
  const hours = [];
  for (let i = 167; i >= 0; i--) {
    const d = new Date(now.getTime() - i * 3600000);
    d.setMinutes(0, 0, 0);
    hours.push({ ts: d.toISOString(), count: 0 });
  }
  const idx = new Map(hours.map((h, i) => [h.ts.slice(0, 13), i]));
  for (const b of buckets) {
    const k = (b.ts || "").slice(0, 13);
    const i = idx.get(k);
    if (i != null) hours[i].count = b.count || 0;
  }
  const maxCount = Math.max(1, ...hours.map((h) => h.count));
  const barW = (width - pad * 2) / hours.length;
  const svg =
    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
    hours
      .map((h, i) => {
        const x = pad + i * barW;
        const bh = (h.count / maxCount) * (height - pad * 2);
        const y = height - pad - bh;
        const color = h.count > 0 ? "var(--accent, #4a90e2)" : "var(--border, #ddd)";
        return `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${Math.max(1, barW - 0.5).toFixed(1)}" height="${Math.max(1, bh).toFixed(1)}" fill="${color}" />`;
      })
      .join("") +
    `</svg>`;
  const totalCount = hours.reduce((a, h) => a + h.count, 0);
  return el("div", {}, [
    el(
      "div",
      { class: "muted small", style: "margin-bottom:4px;" },
      `Activity, last 7 days (${totalCount} event${totalCount === 1 ? "" : "s"})`,
    ),
    el("div", { html: svg }),
  ]);
}

function _funnelBar(label, count, total, accent) {
  const pct = total > 0 ? Math.min(100, (count / total) * 100) : 0;
  return el("div", { style: "margin-bottom:6px;" }, [
    el(
      "div",
      { style: "display:flex;justify-content:space-between;font-size:11px;margin-bottom:2px;" },
      [
        el("span", {}, label),
        el("span", { class: "muted" }, `${fmtNum(count)} / ${fmtNum(total)} (${pct.toFixed(0)}%)`),
      ],
    ),
    el("div", { style: "background:var(--bg-2);border-radius:3px;height:8px;overflow:hidden;" }, [
      el("div", {
        style: `width:${pct}%;height:100%;background:${accent || "var(--accent, #4a90e2)"};`,
      }),
    ]),
  ]);
}

const CHANNEL_ICONS = {
  x: "🐦",
  twitter: "🐦",
  linkedin: "🔗",
  telegram: "✈️",
  email: "✉️",
  web: "🌐",
};
const CHANNEL_COLORS = {
  x: "#1da1f2",
  twitter: "#1da1f2",
  linkedin: "#0077b5",
  telegram: "#229ed9",
  email: "#ea4335",
};

function _channelStatusBadge(status) {
  const map = {
    not_started: { cls: "badge-gray", label: "Not started" },
    queued: { cls: "badge-blue", label: "Queued" },
    scheduled: { cls: "badge-blue", label: "Scheduled" },
    in_progress: { cls: "badge-yellow", label: "In progress" },
    sent: { cls: "badge-green", label: "Sent" },
    replied: { cls: "badge-green", label: "Replied" },
    failed: { cls: "badge-red", label: "Failed" },
    skipped: { cls: "badge-gray", label: "Skipped" },
  };
  const m = map[status] || { cls: "badge-gray", label: status || "—" };
  return el("span", { class: `badge ${m.cls}` }, m.label);
}

async function renderCampaignDetail({ type, id }) {
  showLoading();
  const data = await api("campaign-detail", { type, id });
  if (data?.error) {
    showError(data.error, () => renderCampaignDetail({ type, id }));
    return;
  }
  const {
    campaign,
    messages,
    events,
    stats,
    funnel,
    activity,
    lastEvent,
    nextAction,
    channels,
    channelColumns,
    inbound,
    tracking,
  } = data;

  const overallStatus = campaign.status || campaign.overall_status || "—";
  const isActive = ["running", "active"].includes(overallStatus);
  const isPaused = overallStatus === "paused";

  // Status pill colour
  const statusPillClass = isActive ? "badge-green" : isPaused ? "badge-yellow" : "badge-gray";

  // ── Action buttons (pause/resume)
  async function doAction(operation) {
    const r = await api("campaign-action", { type, id, operation });
    if (r?.error) {
      toast(`Error: ${r.error}`, "err");
      return;
    }
    toast(`Campaign ${operation}d`, "ok");
    renderCampaignDetail({ type, id });
  }

  // ── Funnel / stats card
  const funnelCard = (() => {
    if (type === "dm" || type === "email") {
      const total = funnel?.total || 0;
      const sent = funnel?.sent || 0;
      const replied = funnel?.replied || tracking?.reply || stats?.replied || 0;
      const failed = funnel?.failed || stats?.failed || 0;
      const queued = funnel?.queued || 0;
      const opened = type === "email" ? tracking?.open || 0 : null;
      const clicked = type === "email" ? tracking?.click || 0 : null;
      const bounced = type === "email" ? tracking?.bounce || funnel?.bounced || 0 : null;

      return el("div", { class: "card" }, [
        el("div", { class: "card-title" }, "Funnel"),
        _funnelBar("Sent", sent, total, "#4a90e2"),
        type === "email" ? _funnelBar("Opened", opened, sent || total, "#7c6bff") : null,
        type === "email" ? _funnelBar("Clicked", clicked, sent || total, "#5fb37c") : null,
        _funnelBar("Replied", replied, total, "#0d652d"),
        type === "email" ? _funnelBar("Bounced", bounced, total, "#d93025") : null,
        _funnelBar("Failed", failed, total, "#d93025"),
        queued > 0 ? _funnelBar("Queued (waiting)", queued, total, "#888") : null,
      ]);
    }
    // Outreach
    return el("div", { class: "stats-grid" }, [
      statCard("Outbound actions", fmtNum(stats?.sent || 0)),
      statCard("Replies received", fmtNum(stats?.replied || 0)),
      statCard("Connections accepted", fmtNum(stats?.accepted || 0)),
      statCard("Failures", fmtNum(stats?.failed || 0)),
    ]);
  })();

  // ── Per-channel card (outreach only)
  const channelsCard =
    type !== "outreach"
      ? null
      : (() => {
          const cols = channelColumns || {};
          const channelEntries = Object.entries(cols).filter(([k]) =>
            ["x", "linkedin", "telegram", "email"].includes(k),
          );
          return el("div", { class: "card" }, [
            el("div", { class: "card-title" }, "Channels"),
            el(
              "div",
              { style: "display:flex;flex-direction:column;gap:8px;" },
              channelEntries.map(([ch, info]) => {
                const stat = (channels || []).find(
                  (c) => c.platform === ch || (ch === "x" && c.platform === "twitter"),
                );
                return el(
                  "div",
                  {
                    style:
                      "display:flex;align-items:center;gap:12px;padding:10px;background:var(--bg-2);border-radius:6px;border-left:3px solid " +
                      (CHANNEL_COLORS[ch] || "#999") +
                      ";",
                  },
                  [
                    el("span", { style: "font-size:18px;" }, CHANNEL_ICONS[ch] || "•"),
                    el("div", { style: "flex:1;min-width:0;" }, [
                      el(
                        "div",
                        { style: "font-weight:600;font-size:13px;text-transform:capitalize;" },
                        ch,
                      ),
                      el(
                        "div",
                        { class: "muted small", style: "margin-top:2px;" },
                        stat
                          ? `${stat.count} action${stat.count === 1 ? "" : "s"} · ` +
                              (stat.inboundCount > 0 ? `${stat.inboundCount} inbound · ` : "") +
                              `last ${fmtDate(stat.lastAt)}`
                          : "no activity",
                      ),
                    ]),
                    _channelStatusBadge(info.status),
                  ],
                );
              }),
            ),
          ]);
        })();

  // ── Inbound notifications (outreach only)
  const inboundCard =
    type !== "outreach" || !inbound || inbound.length === 0
      ? null
      : el("div", { class: "card" }, [
          el("div", { class: "card-title" }, `Inbound from this contact (${inbound.length})`),
          el(
            "div",
            {},
            inbound.slice(0, 8).map((n) =>
              el(
                "div",
                {
                  style:
                    "display:flex;gap:8px;padding:6px 0;border-bottom:1px solid var(--border);font-size:12px;",
                },
                [
                  el("span", { style: "font-size:14px;" }, CHANNEL_ICONS[n.platform] || "•"),
                  el(
                    "span",
                    { class: "muted small mono", style: "min-width:55px;" },
                    n.notification_type,
                  ),
                  el(
                    "span",
                    {
                      style:
                        "flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;",
                    },
                    n.preview_text || n.notification_type,
                  ),
                  el("span", { class: "muted small" }, fmtDate(n.received_at)),
                ],
              ),
            ),
          ),
        ]);

  // ── Recent activity table
  const recentRows = messages || events || [];
  const recentTable = el("div", { class: "card" }, [
    el("div", { class: "card-title" }, type === "outreach" ? "Recent events" : "Recent messages"),
    recentRows.length === 0
      ? el("div", { class: "muted small" }, "No activity yet")
      : el("table", { class: "table" }, [
          el(
            "tbody",
            {},
            recentRows.slice(0, 30).map((m) => {
              const actorLabel =
                m.recipient_username ||
                m.recipient_email ||
                (m.platform ? `${CHANNEL_ICONS[m.platform] || "•"} ${m.platform}` : "—");
              return el("tr", {}, [
                el("td", {}, actorLabel),
                el("td", {}, [
                  el(
                    "span",
                    { class: "badge " + statusClass(m.status || m.event_type) },
                    m.status || m.event_type || "—",
                  ),
                ]),
                el("td", { class: "secondary-cell" }, fmtDate(m.sent_at || m.created_at)),
                m.detail || m.error_message
                  ? el(
                      "td",
                      {
                        class: "muted small",
                        style:
                          "max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;",
                      },
                      (m.detail || m.error_message || "").slice(0, 80),
                    )
                  : null,
              ]);
            }),
          ),
        ]),
  ]);

  const content = el("div", {}, [
    el("div", { class: "page-header" }, [
      el("div", {}, [
        el(
          "button",
          { class: "btn btn-secondary", onclick: () => navigate("campaigns") },
          "« Back",
        ),
        el(
          "div",
          {
            class: "page-title",
            style: "margin-top:10px;display:flex;align-items:center;gap:8px;",
          },
          [
            el("span", {}, campaign.name || campaign.subject || `Campaign #${campaign.id}`),
            el("span", { class: `badge ${statusPillClass}` }, overallStatus),
          ],
        ),
        el(
          "div",
          { class: "page-subtitle" },
          `${type}` +
            (campaign.contact_name ? ` · ${campaign.contact_name}` : "") +
            (campaign.company_name ? ` @ ${campaign.company_name}` : ""),
        ),
      ]),
      el("div", { style: "display:flex;gap:8px;" }, [
        isActive
          ? el(
              "button",
              { class: "btn btn-secondary", onclick: () => doAction("pause") },
              "⏸ Pause",
            )
          : null,
        isPaused
          ? el(
              "button",
              { class: "btn btn-primary", onclick: () => doAction("resume") },
              "▶ Resume",
            )
          : null,
        el(
          "button",
          { class: "btn btn-secondary", onclick: () => renderCampaignDetail({ type, id }) },
          "↻ Refresh",
        ),
      ]),
    ]),

    // 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,

    // Funnel / stats
    funnelCard,

    // Activity sparkline
    el("div", { class: "card" }, [
      _activitySparkline(activity || [], { width: 720, height: 64 }),
      lastEvent?.sent_at
        ? el(
            "div",
            { class: "muted small", style: "margin-top:6px;" },
            `Last activity: ${fmtDate(lastEvent.sent_at)} (${lastEvent.status || "—"})`,
          )
        : null,
    ]),

    channelsCard,
    inboundCard,
    recentTable,
  ]);
  setContentNode(content);
}
