// mailroom-wizard.jsx — New-campaign wizard (8 steps). The centerpiece.
// Leads(offer/ICP) → Domains → Mapping → Sequence → Follow-up → Schedule →
// Review → Launch. Exports: ViewWizard.

const W_STEPS = ["Leads", "Domains", "Mapping", "Sequence", "Follow-up", "Schedule", "Review", "Launch"];

function ViewWizard({ onExit, startStep = 0 }) {
  const t = useT();
  const [step, setStep] = React.useState(startStep);
  const [launched, setLaunched] = React.useState(false);
  const go = (i) => setStep(Math.max(0, Math.min(7, i)));

  return (
    <div style={{ height: "100%", width: "100%", display: "flex", flexDirection: "column",
      background: t.bg, color: t.text, fontFamily: t.font }}>
      {/* top bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "0 16px", height: 52,
        background: t.console, color: t.consoleText, flex: "0 0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 18, height: 18, borderRadius: 4, background: t.accent, display: "flex",
            alignItems: "center", justifyContent: "center" }}><Icon name="mail" size={11} color="#fff" sw={2.2} /></span>
          <span style={{ fontFamily: t.head, fontWeight: 700, fontSize: 14 }}>Mailroom</span>
          <Icon name="chevR" size={13} color={t.consoleMuted} />
          <span style={{ fontWeight: 600, fontSize: 13, color: t.consoleMuted }}>New campaign</span>
        </div>
        <div style={{ width: 1, height: 20, background: hexA("#fff", 0.15) }} />
        <input defaultValue="RevOps leaders · NA" style={{ border: "none", outline: "none", background: "transparent",
          font: "inherit", fontSize: 13.5, fontWeight: 600, color: t.consoleText, width: 220, fontFamily: t.font }} />
        <Chip tone="console">draft</Chip>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12, color: t.consoleMuted, display: "flex", alignItems: "center", gap: 5 }}>
          <Icon name="check" size={13} color={t.good} /> autosaved</span>
        <button onClick={onExit} title="Close" style={{ width: 30, height: 30, borderRadius: 5, border: "none",
          background: "transparent", color: t.consoleMuted, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="x" size={17} /></button>
      </div>

      {/* stepper */}
      <div style={{ display: "flex", alignItems: "center", gap: 2, padding: "10px 16px", background: t.bg,
        borderBottom: `1px solid ${t.border}`, flex: "0 0 auto", overflowX: "auto" }}>
        {W_STEPS.map((label, i) => {
          const done = i < step, cur = i === step;
          return (
            <React.Fragment key={label}>
              <button onClick={() => go(i)} style={{ display: "flex", alignItems: "center", gap: 8, border: "none",
                background: "transparent", cursor: "pointer", padding: "4px 6px", borderRadius: t.radiusSm,
                opacity: !done && !cur && i > step ? 0.55 : 1 }}>
                <span style={{ width: 22, height: 22, borderRadius: t.radiusSm, flex: "0 0 auto", display: "flex",
                  alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, fontFamily: t.mono,
                  background: cur ? t.accent : done ? t.accent : "transparent",
                  color: cur || done ? "#fff" : t.textMuted, border: cur || done ? "none" : `1px solid ${t.borderStrong}` }}>
                  {done ? <Icon name="check" size={12} sw={2.6} /> : i + 1}</span>
                <span style={{ fontSize: 12.5, fontWeight: cur ? 700 : 500, color: cur ? t.text : t.textSec, whiteSpace: "nowrap" }}>{label}</span>
              </button>
              {i < W_STEPS.length - 1 && <div style={{ width: 16, height: 2, background: i < step ? t.accent : t.border, flex: "0 0 auto", borderRadius: 1 }} />}
            </React.Fragment>
          );
        })}
      </div>

      {/* body */}
      <div style={{ flex: 1, minHeight: 0, overflowY: "auto" }}>
        {step === 0 && <StepLeads />}
        {step === 1 && <StepDomains />}
        {step === 2 && <StepMapping />}
        {step === 3 && <StepSequence />}
        {step === 4 && <StepFollowup />}
        {step === 5 && <StepSchedule />}
        {step === 6 && <StepReview go={go} />}
        {step === 7 && <StepLaunch launched={launched} setLaunched={setLaunched} onExit={onExit} />}
      </div>

      {/* footer */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "0 18px", height: 60,
        background: t.bg, borderTop: `1px solid ${t.border}`, flex: "0 0 auto" }}>
        <Btn kind="ghost" icon="chevL" onClick={() => go(step - 1)} style={{ visibility: step === 0 ? "hidden" : "visible" }}>Back</Btn>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12, color: t.textMuted, fontFamily: t.mono }}>step {step + 1} / 8 · {W_STEPS[step].toLowerCase()}</span>
        {step < 6
          ? <Btn kind="primary" iconR="arrowR" onClick={() => go(step + 1)}>Continue</Btn>
          : step === 6
            ? <Btn kind="primary" iconR="rocket" onClick={() => go(7)}>Launch (creates paused)</Btn>
            : <Btn kind="soft" onClick={onExit}>Done</Btn>}
      </div>
    </div>
  );
}

/* ---------- shared ---------- */
function FormStep({ title, sub, children, width = 860 }) {
  const t = useT();
  return (
    <div style={{ padding: "28px 20px 48px" }}>
      <div style={{ maxWidth: width, margin: "0 auto" }}>
        <div style={{ marginBottom: 22 }}>
          <div style={{ fontFamily: t.head, fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: "-.02em" }}>{title}</div>
          {sub && <div style={{ fontSize: 14, color: t.textMuted, marginTop: 5, lineHeight: 1.5 }}>{sub}</div>}
        </div>
        {children}
      </div>
    </div>
  );
}

/* ---------- STEP 1 · Leads (offer / ICP) ---------- */
function StepLeads() {
  const t = useT();
  const [offer, setOffer] = React.useState("Cold-email infrastructure for B2B SaaS — we get your outbound landing in the primary inbox without the $400/mo tool stack.");
  const [icp, setIcp] = React.useState("RevOps and demand-gen leaders at Series A–B SaaS companies in North America, 50–250 employees, currently scaling outbound.");
  const extracted = [
    { k: "titles", v: ["VP RevOps", "Head of Demand Gen", "Growth Lead"] },
    { k: "industries", v: ["B2B SaaS"] },
    { k: "stage", v: ["Series A", "Series B"] },
    { k: "headcount", v: ["50–250"] },
    { k: "geo", v: ["United States", "Canada"] },
  ];
  return (
    <FormStep title="What are you selling, and to whom?" width={920}
      sub="Write it like you'd say it. The AI writes the targeting and the copy — you approve every gate before anything sends.">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 18 }}>
        <Card>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <Icon name="bolt" size={15} color={t.accent} /><Label>Your offer</Label>
          </div>
          <Field area rows={5} value={offer} onChange={setOffer} placeholder="What you sell, and the wedge…" />
        </Card>
        <Card>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <Icon name="target" size={15} color={t.accent} /><Label>Who to target (ICP)</Label>
          </div>
          <Field area rows={5} value={icp} onChange={setIcp} placeholder="Titles, company type, size, geo…" />
        </Card>
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
        <Icon name="sparkle" size={15} color={t.accent} />
        <Label style={{ color: t.accentText }}>AI extracted</Label>
        <span style={{ fontSize: 12, color: t.textMuted }}>— parsed from your inputs · edit any chip</span>
      </div>
      <Card sunken>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {extracted.map((row) => (
            <div key={row.k} style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <Mono style={{ fontSize: 11.5, color: t.textMuted, width: 92, flex: "0 0 auto", textAlign: "right" }}>{row.k}</Mono>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {row.v.map((v) => (
                  <span key={v} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 10px", borderRadius: 999,
                    background: t.accentTint, border: `1px solid ${t.accentBorder}`, color: t.accentText, fontSize: 12.5, fontWeight: 600 }}>
                    {v}<Icon name="x" size={11} color={t.accentText} /></span>
                ))}
                <span style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "4px 9px", borderRadius: 999,
                  background: "transparent", border: `1px dashed ${t.borderStrong}`, color: t.textMuted, fontSize: 12.5, cursor: "pointer" }}>
                  <Icon name="plus" size={11} /> add</span>
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16, paddingTop: 14, borderTop: `1px solid ${t.border}` }}>
          <Icon name="users" size={15} color={t.good} />
          <span style={{ fontSize: 13, color: t.textSec }}>Estimated <Mono style={{ fontWeight: 700, color: t.text }}>~4,200</Mono> matching leads in Airscale. The agent will pull and verify them at the Leads stage.</span>
        </div>
      </Card>
    </FormStep>
  );
}

/* ---------- STEP 2 · Domains ---------- */
function StepDomains() {
  const t = useT();
  const owned = [
    { d: "reachgrid.co", boxes: 3, status: "warm", on: true },
    { d: "trygrid.io", boxes: 3, status: "warm", on: true },
    { d: "gridmail.co", boxes: 3, status: "warming", on: false },
  ];
  const newD = [
    { d: "revopsreach.co", price: "$11.98", avail: true },
    { d: "getrevops.io", price: "$13.99", avail: true },
    { d: "revopshq.co", price: "$12.98", avail: true },
    { d: "revops.email", price: "—", avail: false },
  ];
  const [sel, setSel] = React.useState({ "reachgrid.co": true, "trygrid.io": true });
  const [buy, setBuy] = React.useState({ "revopsreach.co": true, "getrevops.io": true });
  const buyTotal = newD.filter((x) => buy[x.d] && x.avail).reduce((s, x) => s + parseFloat(x.price.replace("$", "")), 0);

  return (
    <FormStep title="Domains & sending mailboxes" width={920}
      sub="Attach domains you already warmed, or have the agent register fresh ones. Sending happens from these.">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {/* attach owned */}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <Icon name="server" size={15} color={t.textSec} /><Label>Attach owned</Label>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {owned.map((o) => {
              const on = !!sel[o.d];
              return (
                <div key={o.d} onClick={() => setSel({ ...sel, [o.d]: !on })} style={{ display: "flex", alignItems: "center", gap: 11,
                  padding: "12px 13px", borderRadius: t.radiusSm, cursor: "pointer",
                  border: `1px solid ${on ? t.accentBorder : t.border}`, background: on ? t.accentTint : t.card }}>
                  <span style={{ width: 17, height: 17, borderRadius: 4, border: `1.5px solid ${on ? t.accent : t.borderStrong}`,
                    background: on ? t.accent : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
                    {on && <Icon name="check" size={11} color="#fff" sw={3} />}</span>
                  <Icon name="globe" size={15} color={t.accent} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <Mono style={{ fontSize: 13, fontWeight: 600 }}>{o.d}</Mono>
                    <div style={{ fontSize: 11, color: t.textMuted }}>{o.boxes} mailboxes</div>
                  </div>
                  {o.status === "warm" ? <Chip tone="good" icon="check">warm</Chip> : <Chip tone="warn" icon="flame">warming</Chip>}
                </div>
              );
            })}
          </div>
        </div>

        {/* register new */}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <Icon name="globe" size={15} color={t.textSec} /><Label>Register new</Label>
          </div>
          {/* spends money banner */}
          <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 12px", borderRadius: t.radiusSm, marginBottom: 10,
            background: t.accentTint, border: `1px solid ${t.accentBorder}` }}>
            <Icon name="dollar" size={15} color={t.accent} />
            <span style={{ fontSize: 12, color: t.accentText, fontWeight: 600 }}>Spends money — approval required before purchase</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {newD.map((n) => {
              const on = !!buy[n.d];
              return (
                <div key={n.d} onClick={() => n.avail && setBuy({ ...buy, [n.d]: !on })} style={{ display: "flex", alignItems: "center", gap: 11,
                  padding: "12px 13px", borderRadius: t.radiusSm, cursor: n.avail ? "pointer" : "default", opacity: n.avail ? 1 : 0.55,
                  border: `1px solid ${on ? t.accentBorder : t.border}`, background: on ? t.accentTint : t.card }}>
                  <span style={{ width: 17, height: 17, borderRadius: 4, border: `1.5px solid ${on ? t.accent : t.borderStrong}`,
                    background: on ? t.accent : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
                    {on && <Icon name="check" size={11} color="#fff" sw={3} />}</span>
                  <Mono style={{ fontSize: 13, fontWeight: 600, flex: 1 }}>{n.d}</Mono>
                  {n.avail ? <Chip tone="good">available</Chip> : <Chip tone="bad">taken</Chip>}
                  <Mono style={{ fontSize: 12.5, fontWeight: 700, color: n.avail ? t.text : t.textMuted, width: 56, textAlign: "right" }}>{n.price}</Mono>
                </div>
              );
            })}
          </div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12, padding: "11px 13px",
            borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}` }}>
            <span style={{ fontSize: 12.5, color: t.textSec }}>{Object.values(buy).filter(Boolean).length} new domains · via Namecheap</span>
            <Mono style={{ fontSize: 14, fontWeight: 700, color: t.accent }}>${buyTotal.toFixed(2)}</Mono>
          </div>
        </div>
      </div>
    </FormStep>
  );
}

/* ---------- STEP 3 · Mapping ---------- */
function StepMapping() {
  const t = useT();
  const rows = [
    { col: "email", field: "Email", sample: "dana@northwind.io", req: true },
    { col: "first_name", field: "First name", sample: "Dana", ok: true },
    { col: "company", field: "Company", sample: "Northwind SaaS", ok: true },
    { col: "title", field: "Job title", sample: "VP RevOps", ok: true },
    { col: "linkedin", field: "Custom · linkedin", sample: "linkedin.com/in/…", ok: true },
    { col: "notes", field: "Don't import", sample: "—", skip: true },
  ];
  return (
    <FormStep title="Map the lead fields" sub="Auto-matched 5 of 6. These fields power your {{merge_tags}} in the sequence.">
      <Card pad={false} style={{ overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 30px 1fr 1fr", padding: "10px 16px", borderBottom: `1px solid ${t.border}`, background: t.sunken }}>
          {["Source field", "", "Mailroom field", "Sample"].map((h, i) => <Label key={i}>{h}</Label>)}
        </div>
        {rows.map((r, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 30px 1fr 1fr", alignItems: "center",
            padding: "11px 16px", borderBottom: i < rows.length - 1 ? `1px solid ${t.border}` : "none" }}>
            <Mono style={{ fontSize: 12.5, fontWeight: 600 }}>{r.col}</Mono>
            <Icon name="arrowR" size={14} color={t.textMuted} />
            <div style={{ display: "flex", alignItems: "center", gap: 8, height: t.ctrlH, border: `1px solid ${t.borderStrong}`,
              borderRadius: t.radiusSm, padding: "0 11px", background: r.skip ? t.sunken : t.raise, maxWidth: 220 }}>
              <span style={{ flex: 1, fontSize: 13, color: r.skip ? t.textMuted : t.text }}>{r.field}</span>
              <Icon name="chevD" size={14} color={t.textMuted} />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <Mono style={{ fontSize: 12, color: t.textMuted, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.sample}</Mono>
              {r.req && <Chip tone="accent">required</Chip>}
              {r.ok && <Icon name="checkCircle" size={15} color={t.good} />}
              {r.skip && <Icon name="x" size={14} color={t.textMuted} />}
            </div>
          </div>
        ))}
      </Card>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 14, fontSize: 13, color: t.textSec }}>
        <Icon name="checkCircle" size={15} color={t.good} /> All required fields mapped — ~4,200 rows will import cleanly.
      </div>
    </FormStep>
  );
}

/* ---------- STEP 4 · Sequence ---------- */
const SEQ = [
  { subj: "{{first_name}}, quick one on {{company}}'s outbound", delay: 0,
    body: "Hi {{first_name}},\n\nSaw {{company}} is scaling the GTM team — usually the moment deliverability starts quietly eating your reply rate.\n\nWe run cold-email infra so your sends land in primary, not promotions. Worth a look?" },
  { subj: "", delay: 3,
    body: "Following up, {{first_name}} — happy to send a 2-min teardown of where {{company}}'s domains sit today (spam vs primary). No pitch, just the data." },
  { subj: "", delay: 4,
    body: "{{first_name}}, last one from me. If inbox placement isn't a priority this quarter, totally fair — I'll close the loop. If it is, reply 'send' and I'll share the teardown." },
  { subj: "Re: {{company}}'s outbound", delay: 5,
    body: "Reopening this in case it got buried — the offer stands: free deliverability teardown for {{company}}, whenever timing's right." },
];
function StepSequence() {
  const t = useT();
  const [open, setOpen] = React.useState(0);
  const [vars, setVars] = React.useState(null);
  return (
    <FormStep title="The sequence" width={760}
      sub="4 emails. Edit subject and body inline — the AI wrote a first pass. {{variables}} pull from your mapped fields.">
      <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        {SEQ.map((s, i) => {
          const isOpen = open === i;
          return (
            <div key={i} style={{ display: "flex", gap: 14 }}>
              {/* rail */}
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: "0 0 auto", width: 40 }}>
                <div style={{ width: 32, height: 32, borderRadius: t.radiusSm, background: t.accent, color: "#fff",
                  display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
                  <Mono style={{ fontSize: 13, fontWeight: 700, color: "#fff" }}>{i + 1}</Mono>
                </div>
                {i < SEQ.length - 1 && <div style={{ flex: 1, width: 2, background: t.border, minHeight: 18 }} />}
              </div>
              {/* card */}
              <div style={{ flex: 1, marginBottom: 14 }}>
                {i > 0 && (
                  <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 8, fontSize: 12, color: t.textMuted }}>
                    <Icon name="clock" size={13} color={t.textMuted} />
                    wait <Mono style={{ fontWeight: 700, color: t.text }}>{s.delay} days</Mono>, then:
                  </div>
                )}
                <Card pad={false} style={{ overflow: "hidden", borderColor: isOpen ? t.accentBorder : t.border }}>
                  <div onClick={() => setOpen(isOpen ? -1 : i)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 14px", cursor: "pointer",
                    borderBottom: isOpen ? `1px solid ${t.border}` : "none" }}>
                    <Icon name="mail" size={15} color={t.accent} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <span style={{ fontSize: 13, fontWeight: 600, color: t.text }}>
                        {s.subj ? s.subj : <span style={{ color: t.textMuted, fontStyle: "italic" }}>(blank subject — same thread)</span>}
                      </span>
                    </div>
                    <Chip tone="neutral" mono>{i === 0 ? "day 0" : "day " + SEQ.slice(0, i + 1).reduce((a, x) => a + x.delay, 0)}</Chip>
                    <Icon name={isOpen ? "chevD" : "chevR"} size={15} color={t.textMuted} />
                  </div>
                  {isOpen && (
                    <div style={{ padding: 14 }}>
                      <Field label="Subject" value={s.subj} placeholder="(leave blank to keep same thread)" onChange={() => {}} style={{ marginBottom: 12 }} />
                      <Label style={{ marginBottom: 6 }}>Body</Label>
                      <div style={{ border: `1px solid ${t.borderStrong}`, borderRadius: t.radiusSm, background: t.raise, overflow: "hidden" }}>
                        <textarea defaultValue={s.body} rows={6} style={{ width: "100%", border: "none", outline: "none", resize: "vertical",
                          background: "transparent", padding: "11px 13px", font: "inherit", fontSize: 13.5, color: t.text, lineHeight: 1.6, display: "block" }} />
                        <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 11px", borderTop: `1px solid ${t.border}`, background: t.sunken, position: "relative" }}>
                          <Btn kind="soft" size="sm" icon="braces" onClick={() => setVars(vars === i ? null : i)}>Insert variable</Btn>
                          <Btn kind="soft" size="sm" icon="eye" onClick={() => mrToast("Preview rendered with sample lead", { icon: "eye" })}>Preview</Btn>
                          <Btn kind="accentSoft" size="sm" icon="sparkle" onClick={() => mrToast("AI rewrote this email", { icon: "sparkle" })}>Rewrite</Btn>
                          <div style={{ flex: 1 }} />
                          <span style={{ fontSize: 11.5, color: t.textMuted, display: "flex", alignItems: "center", gap: 5 }}>
                            <Icon name="clock" size={12} /> delay
                            <Mono style={{ fontWeight: 700, color: t.text }}>{s.delay}d</Mono>
                          </span>
                          {vars === i && (
                            <div style={{ position: "absolute", bottom: "calc(100% + 6px)", left: 11, background: t.card, border: `1px solid ${t.borderStrong}`,
                              borderRadius: t.radiusSm, boxShadow: t.shadowMd, padding: 6, display: "flex", flexDirection: "column", gap: 2, zIndex: 5, minWidth: 160 }}>
                              {["{{first_name}}", "{{company}}", "{{title}}", "{{linkedin}}"].map((v) => (
                                <button key={v} onClick={() => setVars(null)} style={{ textAlign: "left", border: "none", background: "transparent", cursor: "pointer",
                                  padding: "6px 9px", borderRadius: 4, fontFamily: t.mono, fontSize: 12.5, color: t.text }}
                                  onMouseEnter={(e) => e.currentTarget.style.background = t.accentTint}
                                  onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>{v}</button>
                              ))}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                </Card>
              </div>
            </div>
          );
        })}
      </div>
      <Btn kind="soft" icon="plus" style={{ marginLeft: 54 }} onClick={() => mrToast("Email step added to sequence", { icon: "mail" })}>Add email</Btn>
    </FormStep>
  );
}

/* ---------- STEP 5 · Follow-up ---------- */
function StepFollowup() {
  const t = useT();
  const [s, setS] = React.useState({ reply: true, click: false, meeting: true, thread: true });
  return (
    <FormStep title="Follow-up rules" width={720} sub="Global behavior across every step. Per-step timing lives in the sequence.">
      <Card style={{ marginBottom: 16 }}>
        <Label style={{ marginBottom: 6 }}>Stop a lead's follow-ups when…</Label>
        <FRow t={t} title="They reply" sub="Cancel the rest of the sequence for that lead"><Toggle on={s.reply} onClick={() => setS({ ...s, reply: !s.reply })} /></FRow>
        <FRow t={t} title="They click a link" sub="Treat a click as intent"><Toggle on={s.click} onClick={() => setS({ ...s, click: !s.click })} /></FRow>
        <FRow t={t} title="They book a meeting" sub="Detected via your booking link" last><Toggle on={s.meeting} onClick={() => setS({ ...s, meeting: !s.meeting })} /></FRow>
      </Card>
      <Card>
        <FRow t={t} title="Keep follow-ups in the same thread" sub="Blank subjects reply in-thread"><Toggle on={s.thread} onClick={() => setS({ ...s, thread: !s.thread })} /></FRow>
        <FRow t={t} title="Max follow-ups per lead" sub="Hard cap regardless of sequence length"><Stepper t={t} value={4} /></FRow>
        <FRow t={t} title="Default wait between steps" sub="Applied to new steps you add" last><Stepper t={t} value={4} unit="days" /></FRow>
      </Card>
    </FormStep>
  );
}
function FRow({ t, title, sub, children, last }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "13px 0", borderBottom: last ? "none" : `1px solid ${t.border}` }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text }}>{title}</div>
        {sub && <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>{sub}</div>}
      </div>
      {children}
    </div>
  );
}
function Stepper({ t, value, unit }) {
  return (
    <div style={{ display: "flex", alignItems: "center", border: `1px solid ${t.borderStrong}`, borderRadius: t.radiusSm, overflow: "hidden", height: t.ctrlH }}>
      <button style={{ width: 30, border: "none", borderRight: `1px solid ${t.border}`, background: t.sunken, cursor: "pointer", color: t.textSec, fontSize: 16 }}>–</button>
      <span style={{ padding: "0 12px", fontFamily: t.mono, fontSize: 13, fontWeight: 700, color: t.text, minWidth: unit ? 70 : 30, textAlign: "center" }}>{value}{unit ? " " + unit : ""}</span>
      <button style={{ width: 30, border: "none", borderLeft: `1px solid ${t.border}`, background: t.sunken, cursor: "pointer", color: t.textSec, fontSize: 16 }}>+</button>
    </div>
  );
}

/* ---------- STEP 6 · Schedule ---------- */
function StepSchedule() {
  const t = useT();
  const days = ["M", "T", "W", "T", "F", "S", "S"];
  const [active, setActive] = React.useState([true, true, true, true, true, false, false]);
  return (
    <FormStep title="Schedule" width={760} sub="When the agent sends, and how fast it ramps.">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <Card>
          <Label style={{ marginBottom: 10 }}>Sending days</Label>
          <div style={{ display: "flex", gap: 6, marginBottom: 18 }}>
            {days.map((d, i) => (
              <button key={i} onClick={() => setActive(active.map((a, j) => j === i ? !a : a))} style={{ width: 36, height: 36, borderRadius: t.radiusSm,
                border: `1px solid ${active[i] ? t.accent : t.border}`, background: active[i] ? t.accent : t.card, color: active[i] ? "#fff" : t.textMuted,
                fontWeight: 700, fontSize: 13, cursor: "pointer", fontFamily: t.mono }}>{d}</button>
            ))}
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <Field label="From" value="9:00 AM" mono style={{ flex: 1 }} onChange={() => {}} />
            <Field label="To" value="5:00 PM" mono style={{ flex: 1 }} onChange={() => {}} />
          </div>
          <div style={{ marginTop: 12 }}><Field label="Timezone" value="Lead's local timezone" onChange={() => {}} /></div>
        </Card>
        <Card>
          <Label style={{ marginBottom: 6 }}>Pace & guardrails</Label>
          <FRow t={t} title="Ramp volume gradually" sub="Protect newly-warmed mailboxes"><Toggle on={true} onClick={() => {}} /></FRow>
          <FRow t={t} title="Match ESP" sub="Google→Google, MS→MS where possible"><Toggle on={true} onClick={() => {}} /></FRow>
          <FRow t={t} title="Sends per mailbox / day" sub="Across all attached mailboxes"><Stepper t={t} value={35} /></FRow>
          <FRow t={t} title="Pause if bounce rate >" sub="Rolling 24h, all mailboxes" last><Stepper t={t} value={"5%"} /></FRow>
        </Card>
      </div>
      <Card style={{ marginTop: 16, display: "flex", alignItems: "center", gap: 16 }}>
        {[["~4,200", "leads"], ["6", "mailboxes"], ["~210/day", "send pace"], ["~9 days", "to complete"]].map(([n, l], i) => (
          <div key={i} style={{ flex: 1, borderLeft: i ? `1px solid ${t.border}` : "none", paddingLeft: i ? 16 : 0 }}>
            <Mono style={{ fontSize: 20, fontWeight: 700, color: t.text }}>{n}</Mono>
            <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>{l}</div>
          </div>
        ))}
      </Card>
    </FormStep>
  );
}

/* ---------- STEP 7 · Review ---------- */
function StepReview({ go }) {
  const t = useT();
  const items = [
    { icon: "target", label: "ICP", value: "VP RevOps · B2B SaaS · Series A–B · 50–250 · US/CA", step: 0 },
    { icon: "globe", label: "Domains", value: "2 owned attached · 2 new (revopsreach.co, getrevops.io)", step: 1 },
    { icon: "mail", label: "Sequence", value: "4 emails · same-thread follow-ups · {{merge}} mapped", step: 3 },
    { icon: "calendar", label: "Schedule", value: "Mon–Fri · 9a–5p lead-local · ramped · 35/mailbox/day", step: 5 },
  ];
  return (
    <FormStep title="Review & launch" width={760}
      sub="One scan before you commit. Launch creates everything paused — nothing sends until you approve the final gate.">
      <Card pad={false} style={{ overflow: "hidden", marginBottom: 16 }}>
        {items.map((it, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 13, padding: "15px 16px", borderBottom: i < items.length - 1 ? `1px solid ${t.border}` : "none" }}>
            <div style={{ width: 32, height: 32, borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}`,
              display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}><Icon name={it.icon} size={16} color={t.textSec} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <Label>{it.label}</Label>
              <div style={{ fontSize: 13, color: t.text, marginTop: 3 }}>{it.value}</div>
            </div>
            <Icon name="checkCircle" size={17} color={t.good} />
            <button onClick={() => go(it.step)} style={{ border: "none", background: "transparent", color: t.accentText, fontWeight: 650, fontSize: 12.5, cursor: "pointer", fontFamily: t.font }}>Edit</button>
          </div>
        ))}
      </Card>
      {/* est spend */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 16px", borderRadius: t.radiusLg,
        background: t.accentTint, border: `1px solid ${t.accentBorder}`, marginBottom: 16 }}>
        <Icon name="dollar" size={18} color={t.accent} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: t.accentText }}>Estimated spend at launch</div>
          <div style={{ fontSize: 12, color: t.textSec, marginTop: 1 }}>2 new domains via Namecheap · charged to your Lithic card on approval</div>
        </div>
        <Mono style={{ fontSize: 18, fontWeight: 700, color: t.accent }}>$25.97</Mono>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "11px 14px", borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}` }}>
        <Icon name="shield" size={15} color={t.textSec} />
        <span style={{ fontSize: 12.5, color: t.textSec }}>Launch creates the campaign <b style={{ color: t.text }}>paused</b>. You'll approve domain purchase, then the final send gate.</span>
      </div>
    </FormStep>
  );
}

/* ---------- STEP 8 · Launch ---------- */
function StepLaunch({ launched, setLaunched, onExit }) {
  const t = useT();
  if (launched) {
    return (
      <div style={{ height: "100%", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
        <div style={{ textAlign: "center", maxWidth: 480 }}>
          <div style={{ width: 72, height: 72, borderRadius: t.radiusLg, background: t.goodTint, margin: "0 auto 22px",
            display: "flex", alignItems: "center", justifyContent: "center", border: `1px solid ${hexA(t.good, 0.3)}` }}>
            <Icon name="check" size={36} color={t.good} sw={2.4} /></div>
          <div style={{ fontFamily: t.head, fontSize: 25, fontWeight: 700, color: t.text, letterSpacing: "-.02em" }}>Created — and paused.</div>
          <div style={{ fontSize: 14.5, color: t.textSec, marginTop: 10, lineHeight: 1.6 }}>
            The agent is buying domains and provisioning mailboxes. You'll get a <b style={{ color: t.text }}>Telegram tap</b> to approve the
            spend, then a final gate before the first email sends. Nothing goes out without you.</div>
          <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 26 }}>
            <Btn kind="soft" icon="grid" onClick={onExit}>Mission Control</Btn>
            <Btn kind="primary" icon="campaigns" onClick={onExit}>View campaign</Btn>
          </div>
        </div>
      </div>
    );
  }
  return (
    <FormStep title="Ready to launch" width={580}>
      <Card style={{ textAlign: "center", padding: 34 }}>
        <div style={{ width: 60, height: 60, borderRadius: t.radiusLg, background: t.accentTint, margin: "0 auto 18px",
          display: "flex", alignItems: "center", justifyContent: "center", border: `1px solid ${t.accentBorder}` }}>
          <Icon name="rocket" size={28} color={t.accent} /></div>
        <div style={{ fontFamily: t.head, fontSize: 18, fontWeight: 700, color: t.text }}>RevOps leaders · NA</div>
        <div style={{ fontSize: 13.5, color: t.textMuted, marginTop: 6 }}>~4,200 leads · 4-step sequence · 6 mailboxes</div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, margin: "18px 0", fontSize: 12.5, color: t.textSec }}>
          <Icon name="dollar" size={14} color={t.accent} /> creates paused · approve <Mono style={{ fontWeight: 700, color: t.text }}>$25.97</Mono> domain spend next
        </div>
        <Btn kind="primary" size="lg" iconR="rocket" full onClick={() => { setLaunched(true); mrToast("Campaign created — paused, awaiting your approval", { tone: "good", icon: "rocket" }); }}>Launch (creates paused)</Btn>
        <div style={{ fontSize: 11.5, color: t.textMuted, marginTop: 12 }}>You approve every gate. Pause or edit any time.</div>
      </Card>
    </FormStep>
  );
}

window.ViewWizard = ViewWizard;
