// mailroom-dashboard.jsx — Mission Control (home): stat cards · 8-stage pipeline
// strip · replies-awaiting preview · approval-pending drawer state.
// Exports: PipelineStrip, ViewDashboard.

const PIPE_STAGES = ["plan", "domains", "provision", "warmup", "sequence", "leads", "assemble", "activate"];

const ACTIVE_PIPELINES = [
  { id: "q3", name: "Q3 · Series-A SaaS founders", at: 7, status: "running", gate: null,
    sub: "sending across 8 mailboxes · 1,240 / 3,000 sent" },
  { id: "revops", name: "RevOps leaders · NA", at: 4, status: "awaiting", gate: "domains",
    sub: "blocked: register 3 new domains — spends money", gateStage: 1 },
  { id: "agency", name: "Agency owners · warm reactivation", at: 6, status: "running", gate: null,
    sub: "pulling leads from Airscale · 940 staged" },
  { id: "cfo", name: "Fractional CFOs · breakup test B", at: 8, status: "paused", gate: null,
    sub: "paused mid-flight · 460 / 1,200 sent" },
];

const AWAITING = [
  { id: 1, cat: "BOOKING", emoji: "🔥📅", conf: 96, name: "Priya Anand", email: "priya@ledgerloop.com", line: "Booked 15 min Friday — send the invite?" },
  { id: 2, cat: "POSITIVE", emoji: "🔥", conf: 92, name: "Dana Whitfield", email: "dana@northwind.io", line: "This is timely. Can you do Thursday?" },
  { id: 3, cat: "OBJECTION", emoji: "⚠️", conf: 81, name: "Aisha Khan", email: "aisha@brightpath.io", line: "Interesting — what's pricing for 12 seats?" },
];

const CAT_TONE = { POSITIVE: "good", BOOKING: "accent", OBJECTION: "warn", NEGATIVE: "bad", UNSUBSCRIBE: "neutral", NOISE: "neutral" };

/* ---------------- 8-stage pipeline strip ---------------- */
function PipelineStrip({ at, gateStage, compact }) {
  const t = useT();
  const node = compact ? 22 : 26;
  return (
    <div style={{ display: "flex", alignItems: "flex-start", width: "100%" }}>
      {PIPE_STAGES.map((s, i) => {
        const done = i < at - 1;
        const current = i === at - 1;
        const gate = gateStage === i;
        const fill = done ? t.accent : current ? (gate ? t.marker : t.accent) : "transparent";
        return (
          <React.Fragment key={s}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6, flex: "0 0 auto", width: compact ? 56 : 72, position: "relative" }}>
              {gate && (
                <div style={{ position: "absolute", top: -19, display: "flex", alignItems: "center", gap: 3,
                  background: t.markerTint, border: `1px solid ${t.markerBorder}`, color: t.markerInk,
                  borderRadius: t.radiusSm, padding: "1px 5px", fontSize: 9.5, fontWeight: 700, whiteSpace: "nowrap",
                  letterSpacing: ".03em", textTransform: "uppercase" }}>
                  <Icon name="flag" size={9} color={t.markerInk} /> needs you
                </div>
              )}
              <div style={{ width: node, height: node, borderRadius: t.radiusSm, flex: "0 0 auto",
                background: fill, border: done || current ? `1px solid ${gate && current ? t.markerBorder : t.accent}` : `1px solid ${t.borderStrong}`,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: done || current ? (gate && current ? t.markerInk : "#fff") : t.textMuted,
                animation: current ? "mrPulse 1.6s ease-in-out infinite" : "none" }}>
                {done ? <Icon name="check" size={compact ? 12 : 14} sw={2.4} />
                  : <span style={{ fontFamily: t.mono, fontSize: compact ? 10 : 11, fontWeight: 700 }}>{i + 1}</span>}
              </div>
              <span style={{ fontSize: compact ? 9.5 : 10.5, fontWeight: current ? 700 : 500,
                color: current ? t.text : done ? t.textSec : t.textMuted, fontFamily: t.mono, letterSpacing: ".01em" }}>{s}</span>
            </div>
            {i < PIPE_STAGES.length - 1 && (
              <div style={{ flex: 1, height: 2, marginTop: node / 2 - 1, minWidth: 8,
                background: i < at - 1 ? t.accent : t.border, borderRadius: 1 }} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

/* ---------------- stat card ---------------- */
function Stat({ icon, label, value, unit, delta, up, tone, accent }) {
  const t = useT();
  const c = accent || t.text;
  return (
    <Card style={{ flex: 1, minWidth: 0, padding: t.pad - 3 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ width: 26, height: 26, borderRadius: t.radiusSm, background: hexA(tone || t.accent, t.dark ? 0.2 : 0.12),
          display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
          <Icon name={icon} size={14} color={tone || t.accent} />
        </div>
        <Label style={{ fontSize: 10 }}>{label}</Label>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: 13 }}>
        <span style={{ fontFamily: t.mono, fontSize: 28, fontWeight: 700, color: t.text, letterSpacing: "-.02em", lineHeight: 1 }}>{value}</span>
        {unit && <span style={{ fontFamily: t.mono, fontSize: 12.5, color: t.textMuted }}>{unit}</span>}
      </div>
      {delta && (
        <div style={{ display: "inline-flex", alignItems: "center", gap: 3, fontSize: 11.5, fontWeight: 650,
          marginTop: 8, color: up ? t.good : t.bad }}>
          <Icon name={up ? "trendUp" : "trendDown"} size={12} color={up ? t.good : t.bad} />{delta}
          <span style={{ color: t.textMuted, fontWeight: 500 }}>vs last week</span>
        </div>
      )}
    </Card>
  );
}

function ViewDashboard({ empty, onNew, setView }) {
  const t = useT();
  const [drawer, setDrawer] = React.useState(null);

  if (empty) return <EmptyDashboard onNew={onNew} />;

  return (
    <>
      <PageHeader title="Mission Control" sub="Tuesday · 4 active pipelines · 6 replies need a decision">
        <Btn kind="soft" icon="refresh" onClick={() => mrToast("Synced — pipelines up to date", { icon: "refresh" })}>Sync</Btn>
        <Btn kind="primary" icon="plus" onClick={onNew}>New campaign</Btn>
      </PageHeader>

      <div style={{ flex: 1, overflowY: "auto", padding: t.pad, display: "flex", flexDirection: "column", gap: t.pad }}>
        {/* stat row */}
        <div style={{ display: "flex", gap: t.gap }}>
          <Stat icon="campaigns" label="Active campaigns" value="3" tone={t.accent} />
          <Stat icon="users" label="Leads in flight" value="6.7" unit="k" tone={t.info} delta="18%" up />
          <Stat icon="replies" label="Replies awaiting you" value="06" tone={t.marker === "#f4d63f" ? "#b8901a" : t.marker} />
          <Stat icon="calendar" label="Booked calls" value="11" tone={t.good} delta="3" up />
          <Stat icon="flame" label="Warmup health" value="84" unit="/100" tone={t.warn} />
        </div>

        {/* pipeline strip */}
        <Card pad={false}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 18px 12px", borderBottom: `1px solid ${t.border}` }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>Active pipelines</span>
              <Chip tone="neutral" mono>8 stages</Chip>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, fontSize: 11, color: t.textMuted }}>
              <LegendDot color={t.accent} label="done" t={t} />
              <LegendDot ring color={t.accent} label="current" t={t} />
              <LegendDot color={t.marker} label="needs you" t={t} />
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {ACTIVE_PIPELINES.map((p, i) => (
              <div key={p.id} style={{ padding: "18px 18px 16px", borderBottom: i < ACTIVE_PIPELINES.length - 1 ? `1px solid ${t.border}` : "none",
                background: p.status === "awaiting" ? t.markerTint : "transparent" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 650, color: t.text }}>{p.name}</span>
                  <StatusChip tone={p.status === "running" ? "good" : p.status === "paused" ? "warn" : "marker"} dotPulse={p.status !== "paused"}>
                    {p.status === "awaiting" ? "awaiting approval" : p.status}
                  </StatusChip>
                  <div style={{ flex: 1 }} />
                  <span style={{ fontSize: 12, color: t.textMuted }}>{p.sub}</span>
                  {p.gate
                    ? <Btn kind="marker" size="sm" icon="flag" onClick={() => setDrawer(p)}>Review</Btn>
                    : <IconBtn icon="arrowR" size={16} onClick={() => setView("campaigns")} />}
                </div>
                <PipelineStrip at={p.at} gateStage={p.gateStage} />
              </div>
            ))}
          </div>
        </Card>

        {/* bottom: awaiting replies + warmup */}
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: t.gap }}>
          <Card pad={false}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 18px 12px", borderBottom: `1px solid ${t.border}` }}>
              <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                <Icon name="replies" size={16} color={t.accent} />
                <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>Replies awaiting you</span>
                <Chip tone="marker" mono>6</Chip>
              </div>
              <button onClick={() => setView("replies")} style={{ border: "none", background: "transparent", color: t.accentText,
                fontWeight: 650, fontSize: 12.5, cursor: "pointer", fontFamily: t.font, display: "flex", alignItems: "center", gap: 4 }}>
                Open inbox <Icon name="arrowR" size={13} color={t.accentText} />
              </button>
            </div>
            {AWAITING.map((r, i) => (
              <div key={r.id} onClick={() => setView("replies")} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 18px",
                borderBottom: i < AWAITING.length - 1 ? `1px solid ${t.border}` : "none", cursor: "pointer" }}>
                <Chip tone={CAT_TONE[r.cat]} style={{ fontFamily: t.mono, flex: "0 0 auto" }}>{r.emoji} {r.cat}</Chip>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 7 }}>
                    <span style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{r.name}</span>
                    <Mono style={{ fontSize: 11.5, color: t.textMuted, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.email}</Mono>
                  </div>
                  <div style={{ fontSize: 12.5, color: t.textSec, marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.line}</div>
                </div>
                <Mono style={{ fontSize: 11, color: t.textMuted, flex: "0 0 auto" }}>{r.conf}%</Mono>
                <Btn kind="primary" size="sm" iconR="send" onClick={(e) => { e.stopPropagation(); mrToast(`Reply sent to ${r.name}`, { tone: "good", icon: "send" }); }}>Approve</Btn>
              </div>
            ))}
          </Card>

          <Card>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <Icon name="flame" size={16} color={t.warn} />
                <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>Warmup heat</span>
              </div>
              <Chip tone="good">healthy</Chip>
            </div>
            {[
              ["reachgrid.co", 98], ["trygrid.io", 93], ["gridmail.co", 72], ["growthgrid.co", 31],
            ].map(([d, v]) => (
              <div key={d} style={{ marginBottom: 13 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5 }}>
                  <Mono style={{ fontSize: 12, color: t.text }}>{d}</Mono>
                  <Mono style={{ fontSize: 12, color: v >= 80 ? t.good : v >= 45 ? t.warn : t.bad, fontWeight: 700 }}>{v}</Mono>
                </div>
                <WarmBar val={v} t={t} h={6} />
              </div>
            ))}
            <div style={{ marginTop: 4, paddingTop: 13, borderTop: `1px solid ${t.border}`, display: "flex", alignItems: "center", gap: 8 }}>
              <Icon name="alertCircle" size={14} color={t.warn} />
              <span style={{ fontSize: 12, color: t.textSec }}><b style={{ color: t.text }}>growthgrid.co</b> warmup stalled — 12d old</span>
            </div>
          </Card>
        </div>
      </div>

      {/* approval drawer */}
      <Drawer open={!!drawer} onClose={() => setDrawer(null)}
        title={drawer ? "Approval needed" : ""}
        sub={drawer ? drawer.name : ""}
        footer={drawer && <>
          <Btn kind="ghost" onClick={() => setDrawer(null)}>Not now</Btn>
          <div style={{ flex: 1 }} />
          <Btn kind="soft" onClick={() => setDrawer(null)}>Edit selection</Btn>
          <Btn kind="primary" icon="check" onClick={() => { setDrawer(null); mrToast("Approved — registering domains via Namecheap", { tone: "good", icon: "globe" }); }}>Approve & spend $39</Btn>
        </>}>
        {drawer && <ApprovalBody t={t} />}
      </Drawer>
    </>
  );
}

function ApprovalBody({ t }) {
  const domains = [
    { d: "revopsreach.co", price: "$11.98", avail: true },
    { d: "getrevops.io", price: "$13.99", avail: true },
    { d: "revopshq.co", price: "$12.98", avail: true },
  ];
  return (
    <>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "12px 14px", borderRadius: t.radiusLg,
        background: t.accentTint, border: `1px solid ${t.accentBorder}`, marginBottom: 18 }}>
        <Icon name="dollar" size={17} color={t.accent} style={{ marginTop: 1 }} />
        <div>
          <div style={{ fontSize: 13, fontWeight: 700, color: t.accentText }}>This spends money — approval required</div>
          <div style={{ fontSize: 12, color: t.textSec, marginTop: 3, lineHeight: 1.5 }}>
            The agent wants to register 3 domains via Namecheap and charge your Lithic card. Nothing sends until you approve.
          </div>
        </div>
      </div>
      <Label style={{ marginBottom: 9 }}>Candidate domains</Label>
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 18 }}>
        {domains.map((d) => (
          <div key={d.d} style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 13px", borderRadius: t.radiusSm,
            border: `1px solid ${t.border}`, background: t.card }}>
            <Icon name="globe" size={15} color={t.accent} />
            <Mono style={{ fontSize: 13, fontWeight: 600, flex: 1 }}>{d.d}</Mono>
            <Chip tone="good" icon="check">available</Chip>
            <Mono style={{ fontSize: 12.5, color: t.text, fontWeight: 700 }}>{d.price}</Mono>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", padding: "12px 0", borderTop: `1px solid ${t.border}` }}>
        <span style={{ fontSize: 13, color: t.textSec }}>3 domains · 1 yr · auto-renew off</span>
        <Mono style={{ fontSize: 14, fontWeight: 700, color: t.text }}>$38.95</Mono>
      </div>
    </>
  );
}

function LegendDot({ color, label, ring, t }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
      <span style={{ width: 9, height: 9, borderRadius: 3, background: ring ? "transparent" : color,
        border: `1.5px solid ${color}` }} />
      {label}
    </span>
  );
}

/* ---------------- empty state ---------------- */
function EmptyDashboard({ onNew }) {
  const t = useT();
  return (
    <>
      <PageHeader title="Mission Control" sub="No campaigns yet" />
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: 30 }}>
        <div style={{ maxWidth: 560, textAlign: "center" }}>
          <div style={{ width: 60, height: 60, borderRadius: t.radiusLg, background: t.accentTint, border: `1px solid ${t.accentBorder}`,
            display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 22px" }}>
            <Icon name="rocket" size={28} color={t.accent} />
          </div>
          <h1 style={{ fontFamily: t.head, fontSize: 28, fontWeight: 700, color: t.text, margin: "0 0 10px", letterSpacing: "-.02em" }}>
            Type your first <Marker>offer</Marker>.
          </h1>
          <p style={{ fontSize: 14.5, color: t.textSec, lineHeight: 1.6, margin: "0 auto 26px", maxWidth: 440 }}>
            One line about what you sell and who you want. The agent buys the domains, warms the mailboxes, writes the
            sequence, pulls the leads, and launches — paused, until you approve every gate.
          </p>
          <div style={{ maxWidth: 460, margin: "0 auto 20px", display: "flex", gap: 9 }}>
            <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 9, height: 46, padding: "0 14px",
              border: `1px solid ${t.borderStrong}`, borderRadius: t.radiusSm, background: t.raise, textAlign: "left" }}>
              <Icon name="sparkle" size={16} color={t.accent} />
              <span style={{ fontSize: 13.5, color: t.textMuted }}>e.g. "Cold email infra for B2B SaaS founders"</span>
            </div>
            <Btn kind="primary" size="lg" iconR="arrowR" onClick={onNew}>Start</Btn>
          </div>
          <div style={{ display: "flex", gap: 18, justifyContent: "center", fontSize: 12, color: t.textMuted, fontFamily: t.mono }}>
            <span>8-stage autopilot</span><span>·</span><span>human approval gates</span><span>·</span><span>one-tap replies</span>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { PipelineStrip, ViewDashboard });
