// dashboard-column-2-event-stream-with-spa.js — extracted verbatim from dashboard.js (pure move).

// ── COLUMN 2 — EVENT STREAM with sparkline ──────────────────────
function renderLiveMapEventStream(data) {
  const allEvents = eventsInRange(data.recentEvents || []);
  // Apply muting (always — overrides every filter)
  const events = allEvents.filter(
    (e) =>
      !liveMapState.mutedKinds.has(e.kind) &&
      !liveMapState.mutedPlatforms.has((e.platform || "").toLowerCase()),
  );
  const filter = liveMapState.eventFilter;
  const filtered =
    filter === "all"
      ? events
      : events.filter(
          (e) =>
            e.kind === filter ||
            (filter === "inbound" && (e.kind === "reply_received" || e.kind === "inbound")),
        );

  // Split pinned vs regular (pinned always shown above the feed regardless of filter/range)
  const pinnedSet = new Set(liveMapState.pinnedEvents);
  const pinnedVisible = (data.recentEvents || []).filter((e) => pinnedSet.has(eventId(e)));

  const filters = [
    ["all", "All"],
    ["outreach_sent", "Out"],
    ["inbound", "In"],
    ["signal", "Signals"],
    ["deal", "Deals"],
    ["enrichment", "Enrich"],
  ];

  // Multi-platform stacked throughput sparkline (one color per platform per minute bucket)
  const stacks = computeStackedEventsPerMinute(events, 60);
  const epmTotal = stacks.totals.reduce((s, n) => s + n, 0);
  const rangeLabel =
    liveMapState.timeRangeSec === 0
      ? "all time"
      : (TIME_RANGES.find(([, sec]) => sec === liveMapState.timeRangeSec) || ["", ""])[0];

  const col = el(
    "div",
    { class: "card", style: "padding:10px;max-height:75vh;display:flex;flex-direction:column;" },
    [
      el(
        "div",
        {
          style: "display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;",
        },
        [
          el("div", { style: "font-weight:600;font-size:13px;" }, `Live event stream`),
          el(
            "span",
            { class: "muted small mono" },
            `${filtered.length}${filter !== "all" ? `/${events.length}` : ""}`,
          ),
        ],
      ),
      // Stacked sparkline + per-platform legend
      el(
        "div",
        { style: "margin-bottom:8px;padding:6px;background:var(--bg-2);border-radius:4px;" },
        [
          el(
            "div",
            {
              style:
                "display:flex;justify-content:space-between;font-size:10px;color:var(--text-4);margin-bottom:2px;",
            },
            [
              el("span", {}, `events / min · last 60min · range: ${rangeLabel}`),
              el("span", { class: "mono" }, `${epmTotal} total`),
            ],
          ),
          el("div", { style: "height:36px;", html: stackedSparkBarsSvg(stacks) }),
          el(
            "div",
            {
              style:
                "display:flex;gap:8px;margin-top:4px;flex-wrap:wrap;font-size:9px;color:var(--text-4);",
            },
            Object.entries(PLATFORM_COLOR)
              .filter(([p]) => stacks.perPlatform[p]?.some((n) => n > 0))
              .map(([p, color]) =>
                el("span", { style: "display:flex;align-items:center;gap:3px;" }, [
                  el("span", {
                    style: `width:8px;height:8px;background:${color};border-radius:1px;`,
                  }),
                  el("span", {}, p),
                ]),
              ),
          ),
        ],
      ),
      el(
        "div",
        { style: "display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px;" },
        filters.map(([id, label]) =>
          el(
            "button",
            {
              type: "button",
              class: `btn btn-tiny ${filter === id ? "btn-primary" : "btn-secondary"}`,
              onclick: () => {
                liveMapState.eventFilter = id;
                persistLiveMapPrefs();
                renderLiveMap();
              },
            },
            label,
          ),
        ),
      ),
    ],
  );

  const stream = el("div", { style: "overflow-y:auto;flex:1;" });

  // Pinned events render as a compact section at the top — survives filter/range changes
  if (pinnedVisible.length > 0) {
    stream.appendChild(
      el(
        "div",
        {
          class: "muted",
          style: "font-size:9px;text-transform:uppercase;letter-spacing:0.06em;padding:4px;",
        },
        `Pinned (${pinnedVisible.length})`,
      ),
    );
    for (const ev of pinnedVisible) stream.appendChild(renderEventStreamRow(ev, true));
    stream.appendChild(
      el("div", { style: "border-bottom:1px solid var(--bg-3);margin:4px 0 8px;" }),
    );
  }

  // Mute summary chip — quick way to see / clear what's hidden
  if (liveMapState.mutedKinds.size > 0 || liveMapState.mutedPlatforms.size > 0) {
    stream.appendChild(
      el(
        "div",
        {
          style:
            "padding:4px 6px;background:var(--bg-3);border-radius:4px;margin-bottom:6px;font-size:10px;display:flex;justify-content:space-between;align-items:center;",
        },
        [
          el(
            "span",
            { class: "muted" },
            `Muted: ${[...liveMapState.mutedKinds, ...liveMapState.mutedPlatforms].join(", ")}`,
          ),
          el(
            "button",
            {
              type: "button",
              class: "btn btn-tiny btn-secondary",
              style: "padding:0 6px;font-size:9px;",
              onclick: () => {
                liveMapState.mutedKinds.clear();
                liveMapState.mutedPlatforms.clear();
                persistPinnedAndMuted();
                renderLiveMap();
              },
            },
            "Unmute all",
          ),
        ],
      ),
    );
  }

  if (filtered.length === 0) {
    stream.appendChild(
      el(
        "div",
        { class: "muted small", style: "padding:20px;text-align:center;" },
        pinnedVisible.length === 0
          ? "No events in the last 2 days for this filter."
          : "No more events for this filter (pinned shown above).",
      ),
    );
  } else {
    for (const ev of filtered) stream.appendChild(renderEventStreamRow(ev, false));
  }

  col.appendChild(stream);
  return col;
}

// Stable ID for an event (composed since the snapshot doesn't carry one consistently).
function eventId(ev) {
  return `${ev.source || ""}-${ev.ts || ""}-${ev.platform || ""}-${(ev.who || "").slice(0, 32)}`;
}

const PLATFORM_DISPLAY_ICONS = {
  x: "🐦",
  twitter: "🐦",
  linkedin: "🔗",
  telegram: "✈",
  email: "✉",
  deals: "💰",
  system: "⚙",
};

// One row of the event stream. Includes a ⋯ menu with quick actions.
function renderEventStreamRow(ev, isPinned) {
  const evId = eventId(ev);
  const icon = PLATFORM_DISPLAY_ICONS[ev.platform] || "•";
  const color = KIND_COLOR[ev.kind] || "var(--text-4)";
  const menuOpen = liveMapState.eventRowMenuOpen === evId;

  return el(
    "div",
    {
      style:
        "position:relative;padding:6px;margin-bottom:4px;border-left:2px solid " +
        color +
        ";background:var(--bg-2);border-radius:4px;font-size:11px;cursor:" +
        (ev.drillTo ? "pointer" : "default") +
        ";",
      onclick: (e) => {
        if (e.target.closest(".ev-row-menu") || e.target.closest(".ev-row-menu-btn")) return;
        if (!ev.drillTo) return;
        if (ev.drillTo.type === "contact") showContactDrawer(ev.drillTo.id);
        else if (ev.drillTo.type === "deal") navigate("deals");
        else if (ev.drillTo.type === "signal") navigate("signals");
      },
    },
    [
      el("div", { style: "display:flex;gap:6px;align-items:center;" }, [
        isPinned ? el("span", { style: "font-size:10px;" }, icon("pin")) : null,
        el("span", { class: "muted mono small", style: "min-width:48px;" }, fmtRel(ev.ts)),
        el("span", {}, icon),
        el(
          "span",
          { style: `color:${color};font-size:9px;text-transform:uppercase;letter-spacing:0.04em;` },
          ev.kind,
        ),
        ev.who
          ? el(
              "span",
              {
                style:
                  "font-weight:600;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;",
              },
              ev.who,
            )
          : null,
        el(
          "button",
          {
            type: "button",
            class: "ev-row-menu-btn",
            style:
              "background:none;border:none;color:var(--text-4);cursor:pointer;font-size:14px;padding:0 4px;line-height:1;",
            title: "Row actions",
            onclick: (e) => {
              e.stopPropagation();
              liveMapState.eventRowMenuOpen = menuOpen ? null : evId;
              renderLiveMap();
            },
          },
          "⋯",
        ),
      ]),
      ev.what
        ? el(
            "div",
            { class: "muted small", style: "margin-top:2px;line-height:1.4;" },
            (ev.what || "").slice(0, 160),
          )
        : null,
      menuOpen ? renderEventRowActionsMenu(ev, evId, isPinned) : null,
    ],
  );
}

function renderEventRowActionsMenu(ev, evId, isPinned) {
  const isKindMuted = liveMapState.mutedKinds.has(ev.kind);
  const isPlatformMuted = liveMapState.mutedPlatforms.has((ev.platform || "").toLowerCase());

  const item = (label, onclick) =>
    el(
      "div",
      {
        style: "padding:6px 10px;cursor:pointer;font-size:11px;",
        onmouseenter: (e) => {
          e.currentTarget.style.background = "var(--bg-3)";
        },
        onmouseleave: (e) => {
          e.currentTarget.style.background = "";
        },
        onclick: (e) => {
          e.stopPropagation();
          onclick();
          liveMapState.eventRowMenuOpen = null;
        },
      },
      label,
    );

  return el(
    "div",
    {
      class: "ev-row-menu",
      style:
        "position:absolute;top:24px;right:6px;background:var(--bg-1);border:1px solid var(--bg-3);border-radius:6px;box-shadow:0 6px 20px rgba(0,0,0,0.4);z-index:50;min-width:200px;padding:4px 0;",
    },
    [
      item("Copy text", () => {
        const text = `[${ev.kind}] ${ev.who || ""} — ${ev.what || ""}`.trim();
        navigator.clipboard.writeText(text).then(
          () => toast("Copied", "ok"),
          () => toast("Clipboard unavailable", "err"),
        );
        renderLiveMap();
      }),
      item(isPinned ? "Unpin" : "Pin to top", () => {
        if (isPinned)
          liveMapState.pinnedEvents = liveMapState.pinnedEvents.filter((id) => id !== evId);
        else {
          liveMapState.pinnedEvents.unshift(evId);
          if (liveMapState.pinnedEvents.length > 10) liveMapState.pinnedEvents.pop();
        }
        persistPinnedAndMuted();
        renderLiveMap();
      }),
      item(isKindMuted ? `Unmute kind (${ev.kind})` : `Mute kind (${ev.kind})`, () => {
        if (isKindMuted) liveMapState.mutedKinds.delete(ev.kind);
        else liveMapState.mutedKinds.add(ev.kind);
        persistPinnedAndMuted();
        renderLiveMap();
      }),
      item(
        isPlatformMuted ? `Unmute platform (${ev.platform})` : `Mute platform (${ev.platform})`,
        () => {
          const p = (ev.platform || "").toLowerCase();
          if (isPlatformMuted) liveMapState.mutedPlatforms.delete(p);
          else liveMapState.mutedPlatforms.add(p);
          persistPinnedAndMuted();
          renderLiveMap();
        },
      ),
    ],
  );
}
