// mailroom-campaigns.jsx — Campaign list. Monospace IDs + metrics, inline
// pause/resume, status chips, row → detail drawer, row menus. Exports: ViewCampaigns.

const CAMP_ROWS = [
  { id: "cmp_8fa2", name: "Q3 · Series-A SaaS founders", stage: 7, sent: 1240, total: 3000, reply: 4.8, pos: 31, status: "running" },
  { id: "cmp_3b71", name: "RevOps leaders · NA", stage: 4, sent: 0, total: 4200, reply: 0, pos: 0, status: "awaiting", gate: "domains" },
  { id: "cmp_9c04", name: "Agency owners · warm reactivation", stage: 6, sent: 940, total: 1500, reply: 6.1, pos: 18, status: "running" },
  { id: "cmp_1d55", name: "Fractional CFOs · breakup test B", stage: 8, sent: 460, total: 1200, reply: 2.2, pos: 4, status: "paused" },
  { id: "cmp_47ae", name: "DTC ops · Q4 outbound", stage: 2, sent: 0, total: 2600, reply: 0, pos: 0, status: "draft" },
  { id: "cmp_6e90", name: "PLG SaaS · expansion", stage: 8, sent: 1980, total: 1980, reply: 4.1, pos: 27, status: "done" },
  { id: "cmp_2f18", name: "VC scouts · intro round", stage: 8, sent: 620, total: 620, reply: 5.4, pos: 14, status: "done" },
];
const CAMP_STATUS = {
  running: { tone: "good", label: "running", pulse: true },
  awaiting: { tone: "marker", label: "awaiting", pulse: true },
  paused: { tone: "warn", label: "paused", pulse: false },
  draft: { tone: "neutral", label: "draft", pulse: false },
  done: { tone: "neutral", label: "done", pulse: false },
};
const STAGE_NAMES = ["plan", "domains", "provision", "warmup", "sequence", "leads", "assemble", "activate"];

function ViewCampaigns({ onNew, setView }) {
  const t = useT();
  const [tab, setTab] = React.useState("all");
  const [q, setQ] = React.useState("");
  const [rows, setRows] = React.useState(CAMP_ROWS);
  const [detail, setDetail] = React.useState(null);

  const counts = {
    all: rows.length,
    running: rows.filter((c) => c.status === "running").length,
    awaiting: rows.filter((c) => c.status === "awaiting").length,
    paused: rows.filter((c) => c.status === "paused").length,
    done: rows.filter((c) => c.status === "done" || c.status === "draft").length,
  };
  const view = rows.filter((c) =>
    (tab === "all" || c.status === tab || (tab === "done" && c.status === "draft")) &&
    c.name.toLowerCase().includes(q.toLowerCase()));

  const setStatus = (id, status, verb) => {
    setRows((rs) => rs.map((c) => c.id === id ? { ...c, status } : c));
    setDetail((d) => d && d.id === id ? { ...d, status } : d);
    if (verb) mrToast(verb, { tone: status === "paused" ? "warn" : "good", icon: status === "paused" ? "pause" : "play" });
  };
  const toggle = (c) => setStatus(c.id, c.status === "running" ? "paused" : "running",
    c.status === "running" ? `Paused “${c.name}”` : `Resumed “${c.name}”`);

  const th = { textAlign: "left", fontSize: 10, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase",
    color: t.textMuted, padding: "0 14px", height: 38, whiteSpace: "nowrap" };
  const td = { padding: "0 14px", fontSize: 13, color: t.text, whiteSpace: "nowrap", verticalAlign: "middle" };

  return (
    <>
      <PageHeader title="Campaigns" sub="7 campaigns · 6,470 emails sent this month"
        tabs={[
          { id: "all", label: "All", count: counts.all },
          { id: "running", label: "Running", count: counts.running },
          { id: "awaiting", label: "Awaiting you", count: counts.awaiting },
          { id: "paused", label: "Paused", count: counts.paused },
          { id: "done", label: "Done & drafts", count: counts.done },
        ]} tab={tab} setTab={setTab}>
        <SearchBox placeholder="Search campaigns" value={q} onChange={setQ} width={220} />
        <Btn kind="primary" icon="plus" onClick={onNew}>New campaign</Btn>
      </PageHeader>

      <div style={{ flex: 1, overflowY: "auto", padding: t.pad }}>
        <Card pad={false} style={{ overflow: "hidden" }}>
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 940 }}>
              <thead>
                <tr style={{ borderBottom: `1px solid ${t.border}`, background: t.sunken }}>
                  <th style={{ ...th, width: "30%" }}>Campaign</th>
                  <th style={th}>Stage</th>
                  <th style={{ ...th, width: 150 }}>Sent</th>
                  <th style={{ ...th, textAlign: "right" }}>Reply rate</th>
                  <th style={{ ...th, textAlign: "right" }}>Positive</th>
                  <th style={th}>Status</th>
                  <th style={{ ...th, width: 96, textAlign: "right" }}></th>
                </tr>
              </thead>
              <tbody>
                {view.length === 0 && (
                  <tr><td colSpan={7} style={{ padding: "52px 16px", textAlign: "center", color: t.textMuted }}>
                    <Icon name="search" size={26} color={t.textMuted} style={{ margin: "0 auto 12px" }} />
                    <div style={{ fontFamily: t.head, fontSize: 15, fontWeight: 700, color: t.text }}>No campaigns match</div>
                    <div style={{ fontSize: 13, marginTop: 5 }}>{q ? `Nothing for “${q}”.` : "Try a different tab."} </div>
                  </td></tr>
                )}
                {view.map((c, i) => {
                  const s = CAMP_STATUS[c.status];
                  const pct = c.total ? Math.round((c.sent / c.total) * 100) : 0;
                  return (
                    <tr key={c.id} onClick={() => setDetail(c)} style={{ borderBottom: i < view.length - 1 ? `1px solid ${t.border}` : "none",
                      height: t.rowH + 12, transition: "background .1s", cursor: "pointer",
                      background: c.status === "awaiting" ? t.markerTint : "transparent" }}
                      onMouseEnter={(e) => { if (c.status !== "awaiting") e.currentTarget.style.background = t.dark ? t.sunken : t.bg; }}
                      onMouseLeave={(e) => { if (c.status !== "awaiting") e.currentTarget.style.background = "transparent"; }}>
                      <td style={td}>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontWeight: 600, color: t.text }}>{c.name}</div>
                          <Mono style={{ fontSize: 11, color: t.textMuted }}>{c.id}</Mono>
                        </div>
                      </td>
                      <td style={td}>
                        <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                          <span style={{ fontFamily: t.mono, fontSize: 11.5, fontWeight: 700, padding: "1px 6px",
                            borderRadius: t.radiusSm, background: t.dark ? t.sunken : t.bg, border: `1px solid ${t.border}`, color: t.textSec }}>
                            {c.stage}/8
                          </span>
                          <span style={{ fontSize: 12, color: t.textMuted }}>{STAGE_NAMES[c.stage - 1]}</span>
                        </div>
                      </td>
                      <td style={td}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          <div style={{ flex: 1, height: 5, borderRadius: 2, background: t.dark ? t.sunken : "#e6ddc9", overflow: "hidden", minWidth: 50 }}>
                            <div style={{ height: "100%", width: `${pct}%`, borderRadius: 2,
                              background: c.status === "paused" ? t.warn : c.status === "done" ? t.textMuted : t.accent }} />
                          </div>
                          <Mono style={{ fontSize: 11, color: t.textMuted, width: 64, textAlign: "right" }}>{c.sent.toLocaleString()}/{(c.total / 1000).toFixed(c.total % 1000 ? 1 : 0)}k</Mono>
                        </div>
                      </td>
                      <td style={{ ...td, textAlign: "right" }}>
                        <Mono style={{ fontWeight: 700, color: c.reply >= 4 ? t.good : c.reply ? t.text : t.textMuted }}>{c.reply ? c.reply + "%" : "—"}</Mono>
                      </td>
                      <td style={{ ...td, textAlign: "right" }}><Mono style={{ color: c.pos ? t.text : t.textMuted }}>{c.pos || "—"}</Mono></td>
                      <td style={td}>
                        {c.gate
                          ? <StatusChip tone="marker" dotPulse>awaiting · {c.gate}</StatusChip>
                          : <StatusChip tone={s.tone} dotPulse={s.pulse}>{s.label}</StatusChip>}
                      </td>
                      <td style={{ ...td, textAlign: "right" }} onClick={(e) => e.stopPropagation()}>
                        <div style={{ display: "flex", alignItems: "center", gap: 2, justifyContent: "flex-end" }}>
                          {(c.status === "running" || c.status === "paused") && (
                            <IconBtn icon={c.status === "running" ? "pause" : "play"} size={15} onClick={() => toggle(c)}
                              title={c.status === "running" ? "Pause" : "Resume"} />
                          )}
                          <Menu items={[
                            { label: "Open details", icon: "eye", onClick: () => setDetail(c) },
                            { label: "Edit campaign", icon: "pencil", onClick: () => mrToast("Opening editor…", { icon: "pencil" }) },
                            { label: "Duplicate", icon: "copy", onClick: () => mrToast(`Duplicated “${c.name}”`, { icon: "copy" }) },
                            { divider: true },
                            { label: "Archive", icon: "trash", danger: true, onClick: () => { setRows((rs) => rs.filter((x) => x.id !== c.id)); mrToast("Campaign archived", { tone: "warn", icon: "trash" }); } },
                          ]} />
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      </div>

      <CampaignDrawer c={detail} onClose={() => setDetail(null)} setView={setView}
        onToggle={() => detail && toggle(detail)} onApprove={() => { detail && setStatus(detail.id, "running", "Gate approved — campaign live"); setDetail(null); }} />
    </>
  );
}

function CampaignDrawer({ c, onClose, onToggle, onApprove, setView }) {
  const t = useT();
  if (!c) return null;
  const s = CAMP_STATUS[c.status];
  const pct = c.total ? Math.round((c.sent / c.total) * 100) : 0;
  const metrics = [
    ["sent", c.sent.toLocaleString()], ["of", c.total.toLocaleString()],
    ["reply rate", c.reply ? c.reply + "%" : "—"], ["positive", c.pos || "—"],
  ];
  return (
    <Drawer open={!!c} onClose={onClose} width={520}
      title={c.name} sub={<span style={{ fontFamily: t.mono }}>{c.id} · stage {c.stage}/8 · {STAGE_NAMES[c.stage - 1]}</span>}
      footer={<>
        {(c.status === "running" || c.status === "paused") &&
          <Btn kind="soft" icon={c.status === "running" ? "pause" : "play"} onClick={onToggle}>{c.status === "running" ? "Pause" : "Resume"}</Btn>}
        <div style={{ flex: 1 }} />
        <Btn kind="soft" icon="replies" onClick={() => { onClose(); setView("replies"); }}>Replies</Btn>
        {c.gate
          ? <Btn kind="primary" icon="flag" onClick={onApprove}>Approve gate</Btn>
          : <Btn kind="primary" icon="eye" onClick={() => mrToast("Opening full report…", { icon: "external" })}>Full report</Btn>}
      </>}>
      <div style={{ marginBottom: 18 }}>
        <StatusChip tone={c.gate ? "marker" : s.tone} dotPulse={s.pulse}>{c.gate ? `awaiting · ${c.gate}` : s.label}</StatusChip>
      </div>

      {c.gate && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 13px", borderRadius: t.radiusSm,
          background: t.markerTint, border: `1px solid ${t.markerBorder}`, marginBottom: 18 }}>
          <Icon name="flag" size={16} color={t.markerInk} />
          <span style={{ fontSize: 12.5, color: t.markerInk, fontWeight: 600 }}>Blocked at <b>{c.gate}</b> — approve to register domains & continue.</span>
        </div>
      )}

      <Label style={{ marginBottom: 10 }}>Pipeline</Label>
      <div style={{ marginBottom: 22 }}><PipelineStrip at={c.stage} gateStage={c.gate ? c.stage - 1 : undefined} compact /></div>

      <Label style={{ marginBottom: 10 }}>Performance</Label>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginBottom: 14 }}>
        {metrics.map(([l, v], i) => (
          <div key={i} style={{ padding: "11px 12px", borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}` }}>
            <Mono style={{ fontSize: 17, fontWeight: 700, color: t.text }}>{v}</Mono>
            <div style={{ fontSize: 10.5, color: t.textMuted, marginTop: 2 }}>{l}</div>
          </div>
        ))}
      </div>
      <div style={{ height: 6, borderRadius: 3, background: t.sunken, overflow: "hidden", marginBottom: 22 }}>
        <div style={{ height: "100%", width: `${pct}%`, background: c.status === "paused" ? t.warn : t.accent }} />
      </div>

      <Label style={{ marginBottom: 10 }}>Sequence</Label>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {["Opener · {{first_name}}, quick one", "Bump · day 3 · same thread", "Value · day 7 · teardown offer", "Breakup · day 12"].map((step, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: t.radiusSm,
            border: `1px solid ${t.border}`, background: t.card }}>
            <span style={{ width: 22, height: 22, borderRadius: t.radiusSm, background: t.accent, color: "#fff", flex: "0 0 auto",
              display: "flex", alignItems: "center", justifyContent: "center", fontFamily: t.mono, fontSize: 11, fontWeight: 700 }}>{i + 1}</span>
            <span style={{ fontSize: 12.5, color: t.textSec }}>{step}</span>
          </div>
        ))}
      </div>
    </Drawer>
  );
}
window.ViewCampaigns = ViewCampaigns;
