/* global React, ReactDOM, Icon, Button, Chip, Avatar, AgentAvatar, Panel, SectionLabel, AgentNote, TONES, NET_ACCOUNTS, NET_SEQUENCE, NET_FALLBACKS, NET_OUTREACH_STATS, ScoreMeter, ProofChip, PathChain, PersonNode, StatusSteps, scoreBand, DEGREE, avColors, makeDraft */
// ============================================================
// Get introduced — overlays for the single-screen graph workspace.
// Detail panel + compose modal + outreach drawer + upsell + no-path +
// sync. No route changes: panels slide over the canvas, modals portal.
// ============================================================
const { useState: useNPan } = React;

const primaryOf = (p) => (p && p.uncertain ? p.leaders[0] : p);
const actionLabel = (path) => {
  if (path.degree === 1) return "Message directly";
  const via = path.introducer ? path.introducer.name : path.bridge;
  return via ? `Request intro via ${via.split(" ")[0]}` : "Request intro";
};

const netTa = {
  width: "100%", boxSizing: "border-box", resize: "vertical", padding: "11px 12px", borderRadius: 8,
  border: "1px solid var(--ink-100)", background: "#fff", fontFamily: "var(--font-sans)",
  fontSize: 13, lineHeight: 1.6, color: "var(--fg-1)", outline: "none",
};

// ---------------- Detail panel (slides in over the canvas) ----------------
function DetailPanel({ persona, def, locked, onClose, onCompose, onUpsell }) {
  const path = primaryOf(persona);
  const deg = DEGREE[path.degree] || DEGREE[0];
  const t = TONES[deg.tone];
  return (
    <div style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: 384, background: "#fff", borderLeft: "1px solid var(--ink-100)", boxShadow: "-12px 0 32px rgba(31,27,22,0.08)", zIndex: 25, display: "flex", flexDirection: "column", animation: "cad-slide-in 0.22s cubic-bezier(0.2,0.7,0.1,1) both" }}>
      <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--ink-50)", display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ width: 26, height: 26, borderRadius: 7, background: "var(--paper-sunken)", display: "grid", placeItems: "center", color: "var(--fg-1)", flexShrink: 0 }}><Icon name={def ? def.icon : "contacts"} size={14}/></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="cd-eyebrow" style={{ fontSize: 10.5 }}>{persona.uncertain ? "Department leaders" : (def ? def.label : deg.label + " path")}</div>
        </div>
        <button onClick={onClose} style={iconBtn}><Icon name="close" size={14}/></button>
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <Avatar name={path.target.name} {...avColors(path.target.tone)} size={46}/>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 19, fontWeight: 500, letterSpacing: "-0.01em" }}>{path.target.name}</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-2)" }}>{path.target.title} · {path.target.co}</div>
          </div>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 600, color: t.text, background: t.tint, padding: "3px 10px", borderRadius: 999, whiteSpace: "nowrap" }}>{path.degree === 1 && <Icon name="zap" size={11}/>}{deg.label}</span>
          <ScoreMeter score={path.score} width={150}/>
        </div>

        {locked ? (
          <LockedBlock onUpsell={onUpsell}/>
        ) : (
          <>
            <div style={{ background: "var(--paper-sunken)", borderRadius: 10, padding: "14px 12px" }}>
              <SectionLabel style={{ marginBottom: 10, textAlign: "center", fontSize: 10 }}>The path</SectionLabel>
              <PathChain path={path} vertical/>
            </div>

            <div>
              <SectionLabel style={{ marginBottom: 9, fontSize: 10 }}>Why this works</SectionLabel>
              <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                {(path.proof && path.proof.length ? path.proof : [{ type: "group", text: "Reachable through your network" }]).map((p, i) => <ProofChip key={i} proof={p} full/>)}
              </div>
            </div>

            {path.alternates > 0 && (
              <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--fg-2)", padding: "9px 11px", border: "1px dashed var(--ink-100)", borderRadius: 8 }}>
                <Icon name="route" size={13} style={{ color: "var(--fg-2)" }}/>
                Offerroom found {path.alternates} more {path.alternates === 1 ? "route" : "routes"} to {path.target.name.split(" ")[0]}
              </div>
            )}

            {persona.uncertain && persona.leaders[1] && (
              <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--fg-2)", padding: "9px 11px", border: "1px solid var(--ink-50)", borderRadius: 8 }}>
                <Avatar name={persona.leaders[1].target.name} {...avColors(persona.leaders[1].target.tone)} size={22}/>
                Also: {persona.leaders[1].target.name}, {persona.leaders[1].target.title}
              </div>
            )}
          </>
        )}
      </div>

      {!locked && (
        <div style={{ padding: "13px 18px", borderTop: "1px solid var(--ink-50)", display: "flex", gap: 8 }}>
          <Button variant="primary" size="md" icon={path.degree === 1 ? "send" : "route"} onClick={() => onCompose(persona, def)} style={{ flex: 1, justifyContent: "center" }}>{actionLabel(path)}</Button>
        </div>
      )}
    </div>
  );
}

const LockedBlock = ({ onUpsell }) => (
  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, padding: "20px 8px", textAlign: "center" }}>
    <span style={{ width: 40, height: 40, borderRadius: 999, background: "var(--cardinal-50)", color: "var(--cardinal)", display: "grid", placeItems: "center" }}><Icon name="lock" size={18}/></span>
    <div style={{ fontSize: 13.5, fontWeight: 600 }}>This path is part of Premium</div>
    <div style={{ fontSize: 12.5, color: "var(--fg-2)", lineHeight: 1.5, maxWidth: 240 }}>You can see one path per company on the free plan. Unlock all 4 personas, drafting, and follow-ups.</div>
    <Button variant="primary" size="md" icon="sparkles" onClick={onUpsell}>Unlock with Premium</Button>
  </div>
);

// ---------------- Compose modal (approve-before-send) ----------------
function ComposeModal({ persona, def, onClose, onApprove }) {
  const path = primaryOf(persona);
  const draft = path.draft || makeDraft(path);
  const isIntro = path.degree !== 1;
  const [auto, setAuto] = useNPan(true);
  const [sent, setSent] = useNPan(false);
  const approve = () => { setSent(true); setTimeout(() => onApprove(persona, def), 850); };

  return ReactDOM.createPortal((
    <div className="cad-fade" onClick={onClose} style={modalScrim}>
      <div className="cad-rise" onClick={e => e.stopPropagation()} style={{ width: 560, maxHeight: "90vh", display: "flex", flexDirection: "column", background: "#fff", borderRadius: 14, boxShadow: "0 32px 64px rgba(31,27,22,0.28)" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--ink-50)", display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ width: 30, height: 30, borderRadius: 8, background: "var(--cardinal-50)", color: "var(--cardinal)", display: "grid", placeItems: "center" }}><Icon name={isIntro ? "route" : "send"} size={15}/></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{draft.channel}</div>
            <div style={{ fontSize: 11.5, color: "var(--fg-2)" }}>{isIntro ? "Forwardable, in your voice" : "Direct, grounded in your history"}</div>
          </div>
          <button onClick={onClose} style={iconBtn}><Icon name="close" size={14}/></button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "flex", gap: 11, alignItems: "flex-start", background: "rgba(140,21,21,0.035)", border: "1px solid rgba(140,21,21,0.10)", borderRadius: 10, padding: "12px 13px" }}>
            <AgentAvatar size={24}/>
            <div style={{ fontSize: 12.5, lineHeight: 1.5, color: "var(--fg-1)" }}>{isIntro ? `Drafted for ${(path.introducer ? path.introducer.name : path.bridge || "your contact").split(" ")[0]} to forward. Edit anything. Nothing sends until you approve.` : `A direct note to ${path.target.name.split(" ")[0]}. Edit anything. Nothing sends until you approve.`}</div>
          </div>

          {isIntro && (
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--fg-2)", marginBottom: 7 }}>Subject</div>
              <input defaultValue={`Quick intro to ${path.target.name.split(" ")[0]}?`} style={{ ...netTa, padding: "9px 12px" }}/>
            </div>
          )}

          <div>
            <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--fg-2)", marginBottom: 7 }}>{isIntro ? `Note to ${(path.introducer ? path.introducer.name : path.bridge)}` : `Message to ${path.target.name}`}</div>
            <textarea defaultValue={draft.note} rows={isIntro ? 5 : 6} style={netTa}/>
          </div>

          {isIntro && draft.blurb && (
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--fg-2)", marginBottom: 7, display: "flex", alignItems: "center", gap: 6 }}><Icon name="copy" size={12}/>Forwardable blurb about you</div>
              <textarea defaultValue={draft.blurb} rows={3} style={{ ...netTa, background: "var(--paper-sunken)", fontStyle: "italic" }}/>
            </div>
          )}

          <div style={{ border: "1px solid var(--ink-50)", borderRadius: 10, overflow: "hidden" }}>
            <div style={{ padding: "10px 13px", borderBottom: "1px solid var(--ink-50)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span style={{ fontSize: 12.5, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 7 }}><Icon name="clock" size={14} style={{ color: "var(--cardinal)" }}/>Follow-up sequence</span>
              <button onClick={() => setAuto(a => !a)} style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "none", border: "none", cursor: "pointer", fontFamily: "var(--font-sans)" }}>
                <span style={{ position: "relative", width: 32, height: 18, borderRadius: 999, background: auto ? "#5A7150" : "var(--ink-100)" }}><span style={{ position: "absolute", top: 2, left: auto ? 16 : 2, width: 14, height: 14, borderRadius: 999, background: "#fff", transition: "left 160ms" }}/></span>
                <span style={{ fontSize: 11.5, color: "var(--fg-2)" }}>Auto</span>
              </button>
            </div>
            <div style={{ padding: "4px 13px 10px" }}>
              {NET_SEQUENCE.map((s, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: i < NET_SEQUENCE.length - 1 ? "1px solid var(--ink-50)" : "none", opacity: i > 0 && !auto ? 0.4 : 1 }}>
                  <span style={{ width: 20, height: 20, borderRadius: 999, background: i === 0 ? "var(--cardinal-50)" : "var(--paper-sunken)", color: i === 0 ? "var(--cardinal)" : "var(--fg-2)", display: "grid", placeItems: "center", fontSize: 10.5, fontWeight: 600 }}>{i + 1}</span>
                  <div style={{ flex: 1, fontSize: 12.5 }}>{s.label} <span style={{ color: "var(--fg-2)" }}>· {s.detail}</span></div>
                  <span style={{ fontSize: 11.5, color: "var(--fg-2)", fontFamily: "var(--font-mono)" }}>{s.when}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div style={{ padding: "13px 18px", borderTop: "1px solid var(--ink-50)", display: "flex", alignItems: "center", gap: 9 }}>
          <Button variant="ghost" size="md" icon="trash" onClick={onClose}>Reject</Button>
          <span style={{ flex: 1 }}/>
          <Button variant="secondary" size="md" icon="edit">Save draft</Button>
          <Button variant="primary" size="md" icon={sent ? "check" : "send"} onClick={approve} disabled={sent}>{sent ? "Starting…" : isIntro ? "Approve and request" : "Approve and send"}</Button>
        </div>
      </div>
    </div>
  ), document.body);
}

// ---------------- Outreach drawer (list + thread detail, cross-fade) ----------------
function OutreachDrawer({ threads, onClose }) {
  const [sel, setSel] = useNPan(null);
  return (
    <div style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: 430, background: "#fff", borderLeft: "1px solid var(--ink-100)", boxShadow: "-12px 0 32px rgba(31,27,22,0.10)", zIndex: 30, display: "flex", flexDirection: "column", animation: "cad-slide-in 0.22s cubic-bezier(0.2,0.7,0.1,1) both" }}>
      <div style={{ padding: "15px 18px", borderBottom: "1px solid var(--ink-50)", display: "flex", alignItems: "center", gap: 10 }}>
        {sel ? <button onClick={() => setSel(null)} style={{ ...iconBtn, width: "auto", padding: "0 6px", gap: 5, fontSize: 12.5, color: "var(--fg-2)" }}><Icon name="chevron" size={13} style={{ transform: "rotate(180deg)" }}/>All</button>
             : <span style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 500, flex: 1 }}>Outreach</span>}
        {sel && <span style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{sel.target.name}</span>}
        <button onClick={onClose} style={iconBtn}><Icon name="close" size={14}/></button>
      </div>
      <div className="cad-fade" key={sel ? sel.id : "list"} style={{ flex: 1, overflowY: "auto" }}>
        {sel ? <ThreadDetail thread={sel}/> : (
          <>
            <div style={{ display: "flex", padding: "10px 0", borderBottom: "1px solid var(--ink-50)" }}>
              {NET_OUTREACH_STATS.slice(0, 3).map((s, i) => (
                <div key={i} style={{ flex: 1, textAlign: "center", borderRight: i < 2 ? "1px solid var(--ink-50)" : "none" }}>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500, color: s.tone, lineHeight: 1 }}>{s.n}</div>
                  <div style={{ fontSize: 10, color: "var(--fg-2)", textTransform: "uppercase", letterSpacing: "0.03em", marginTop: 4 }}>{s.label}</div>
                </div>
              ))}
            </div>
            {threads.map(th => <DrawerThreadRow key={th.id} th={th} onOpen={() => setSel(th)}/>)}
          </>
        )}
      </div>
    </div>
  );
}

const DrawerThreadRow = ({ th, onOpen }) => {
  const needsYou = th.next && th.next.toLowerCase().includes("reply");
  return (
    <button onClick={onOpen} style={{ width: "100%", textAlign: "left", display: "flex", alignItems: "center", gap: 12, padding: "13px 18px", background: "#fff", border: "none", borderBottom: "1px solid var(--ink-50)", cursor: "pointer", fontFamily: "var(--font-sans)" }}
      onMouseEnter={e => e.currentTarget.style.background = "var(--paper-hover)"} onMouseLeave={e => e.currentTarget.style.background = "#fff"}>
      <Avatar name={th.target.name} {...avColors(th.target.tone)} size={36}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{th.target.name}</div>
        <div style={{ fontSize: 11.5, color: needsYou ? "var(--cardinal-700)" : "var(--fg-2)" }}>{th.steps[th.statusIndex]}{th.kind === "intro" && th.introducer ? ` · via ${th.introducer.name.split(" ")[0]}` : ""}</div>
      </div>
      {needsYou && <span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--cardinal)" }}/>}
      <Icon name="chevron" size={14} style={{ color: "var(--fg-3)" }}/>
    </button>
  );
};

function ThreadDetail({ thread }) {
  const replied = thread.reply && thread.statusIndex >= thread.steps.length - 1;
  const whoMeta = { you: { icon: "user", label: "You" }, them: { icon: "contacts", label: thread.target.name.split(" ")[0] }, agent: { icon: null, label: "Offerroom" } };
  return (
    <div style={{ padding: 18, display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <Avatar name={thread.target.name} {...avColors(thread.target.tone)} size={42}/>
        <div><div style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 500 }}>{thread.target.name}</div><div style={{ fontSize: 12, color: "var(--fg-2)" }}>{thread.target.title} · {thread.target.co}</div></div>
      </div>
      <div style={{ background: "var(--paper-sunken)", borderRadius: 10, padding: "14px 14px 12px" }}>
        <StatusSteps steps={thread.steps} current={thread.statusIndex} size="sm"/>
        <div style={{ fontSize: 11.5, color: "var(--fg-2)", marginTop: 11, display: "flex", alignItems: "center", gap: 6 }}><Icon name="briefcase" size={12}/>Tracked against {thread.job}</div>
      </div>
      <div>
        <SectionLabel style={{ marginBottom: 12, fontSize: 10 }}>History</SectionLabel>
        {thread.timeline.map((e, i) => {
          const m = whoMeta[e.who];
          return (
            <div key={i} style={{ display: "flex", gap: 11, paddingBottom: i < thread.timeline.length - 1 ? 14 : 0 }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                {e.who === "agent" ? <AgentAvatar size={24}/> : <span style={{ width: 24, height: 24, borderRadius: 999, background: "var(--paper-sunken)", color: "var(--fg-1)", display: "grid", placeItems: "center" }}><Icon name={m.icon} size={12}/></span>}
                {i < thread.timeline.length - 1 && <span style={{ width: 1, flex: 1, minHeight: 14, background: "var(--ink-100)", marginTop: 4 }}/>}
              </div>
              <div style={{ paddingTop: 2 }}>
                <div style={{ fontSize: 12.5 }}><b style={{ fontWeight: 600 }}>{m.label}</b> · {e.time}</div>
                <div style={{ fontSize: 12, color: "var(--fg-2)", marginTop: 1 }}>{e.label}</div>
              </div>
            </div>
          );
        })}
      </div>
      {replied ? (
        <div style={{ borderRadius: 10, border: "1px solid var(--sage-line)", overflow: "hidden" }}>
          <div style={{ padding: "12px 14px", background: "var(--sage-tint)" }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: "var(--sage-text)", marginBottom: 6, display: "flex", alignItems: "center", gap: 6 }}><Icon name="message" size={13}/>{thread.target.name.split(" ")[0]} replied</div>
            <div style={{ fontSize: 12.5, lineHeight: 1.55, color: "var(--ink-700)" }}>{thread.reply}</div>
          </div>
          <div style={{ padding: 13, display: "flex", gap: 8 }}>
            <Button variant="primary" size="sm" icon="send" style={{ flex: 1, justifyContent: "center" }}>Approve reply</Button>
            <Button variant="secondary" size="sm" icon="edit">Edit</Button>
          </div>
        </div>
      ) : (
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 14px", borderRadius: 10, border: "1px solid var(--ink-50)" }}>
          <span style={{ width: 32, height: 32, borderRadius: 8, background: "var(--ochre-tint)", color: "var(--ochre-text)", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name="clock" size={15}/></span>
          <div style={{ flex: 1, fontSize: 12.5 }}><b style={{ fontWeight: 600 }}>Next:</b> {thread.next}<div style={{ color: "var(--fg-2)", marginTop: 1 }}>Drafted for your approval first.</div></div>
        </div>
      )}
    </div>
  );
}

// ---------------- No-path fallback (weak network) ----------------
function NoPathPanel({ companyName }) {
  return (
    <div className="cad-fade" style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", padding: 28, zIndex: 15 }}>
      <div style={{ width: 620, maxWidth: "100%" }}>
        <div style={{ display: "flex", gap: 11, alignItems: "flex-start", background: "rgba(140,21,21,0.04)", border: "1px solid rgba(140,21,21,0.12)", borderRadius: 12, padding: "14px 15px", marginBottom: 14 }}>
          <AgentAvatar size={26}/>
          <div style={{ fontSize: 13, lineHeight: 1.55 }}>No direct path into {companyName} in your network yet. That's not a dead end, it's a smaller first step. Here are 4 ways to make one.</div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {NET_FALLBACKS.map(f => (
            <Panel key={f.key} pad={15} style={{ display: "flex", flexDirection: "column" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ width: 32, height: 32, borderRadius: 8, background: "var(--paper-sunken)", display: "grid", placeItems: "center", color: "var(--fg-1)" }}><Icon name={f.icon} size={16}/></span>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{f.title}</div>
              </div>
              <div style={{ fontSize: 12, color: "var(--fg-2)", lineHeight: 1.5, margin: "9px 0 12px", flex: 1 }}>{f.sub}</div>
              <Button variant="secondary" size="sm" icon="arrow">{f.cta}</Button>
            </Panel>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------------- Upsell modal ----------------
function UpsellModal({ onClose }) {
  const perks = [
    { icon: "contacts", t: "All 4 personas per company", s: "Hiring manager, recruiter, peer, and a senior leader" },
    { icon: "sparkles", t: "Intro drafting in your voice", s: "The forwardable ask, written from your shared history" },
    { icon: "clock", t: "Automated follow-up sequences", s: "Gated follow-ups that stop the moment they reply" },
  ];
  return ReactDOM.createPortal((
    <div className="cad-fade" onClick={onClose} style={modalScrim}>
      <div className="cad-rise" onClick={e => e.stopPropagation()} style={{ width: 460, background: "#fff", borderRadius: 14, boxShadow: "0 32px 64px rgba(31,27,22,0.28)", overflow: "hidden" }}>
        <div style={{ padding: "22px 24px 18px", borderBottom: "1px solid var(--ink-50)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 12 }}>
            <span style={{ width: 38, height: 38, borderRadius: 999, background: "var(--cardinal-50)", color: "var(--cardinal)", display: "grid", placeItems: "center" }}><Icon name="lock" size={18}/></span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--cardinal)", border: "1px solid var(--cardinal-100)", borderRadius: 5, padding: "2px 7px" }}>Premium</span>
          </div>
          <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 23, letterSpacing: "-0.01em", margin: 0 }}>Unlock warm intros</h3>
          <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: "8px 0 0", lineHeight: 1.5 }}>Discovery is free. Drafting the ask and running the follow-ups is Premium.</p>
        </div>
        <div style={{ padding: "16px 24px" }}>
          {perks.map((p, i) => (
            <div key={i} style={{ display: "flex", gap: 12, padding: "10px 0", borderBottom: i < perks.length - 1 ? "1px solid var(--ink-50)" : "none" }}>
              <span style={{ width: 30, height: 30, borderRadius: 8, background: "var(--paper-sunken)", color: "var(--fg-1)", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name={p.icon} size={15}/></span>
              <div><div style={{ fontSize: 13.5, fontWeight: 600 }}>{p.t}</div><div style={{ fontSize: 12, color: "var(--fg-2)", marginTop: 1, lineHeight: 1.4 }}>{p.s}</div></div>
            </div>
          ))}
        </div>
        <div style={{ padding: "4px 24px 22px", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ flex: 1, fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500 }}>$399<span style={{ fontSize: 13, color: "var(--fg-2)", fontFamily: "var(--font-sans)" }}>/mo</span></div>
          <Button variant="ghost" size="md" onClick={onClose}>Not now</Button>
          <Button variant="primary" size="md" icon="sparkles">Upgrade</Button>
        </div>
      </div>
    </div>
  ), document.body);
}

// ---------------- Sync / first-run overlay ----------------
function SyncOverlay({ firstRun, accountsSynced, onDone }) {
  const [phase, setPhase] = useNPan("connect");
  const [pct, setPct] = useNPan(0);
  React.useEffect(() => {
    if (phase !== "syncing") return;
    let p = 0; const t = setInterval(() => { p += 9 + Math.random() * 9; if (p >= 100) { p = 100; clearInterval(t); setTimeout(onDone, 500); } setPct(Math.min(100, Math.round(p))); }, 230);
    return () => clearInterval(t);
  }, [phase]);
  const lines = ["Reading your connections", "Matching past colleagues and alumni", "Scoring paths into your target companies", "Building your network graph"];
  const active = Math.min(lines.length - 1, Math.floor(pct / 25));
  return (
    <div className="cad-fade" style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", padding: 28, background: "var(--paper)", zIndex: 40 }}>
      <div style={{ width: 560, maxWidth: "100%" }}>
        <div style={{ textAlign: "center", marginBottom: 18 }}>
          <div className="cd-eyebrow" style={{ marginBottom: 8 }}>Get introduced</div>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 28, letterSpacing: "-0.02em", margin: 0 }}>{firstRun ? "Connect your network" : "Re-sync your network"}</h2>
          <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: "8px auto 0", maxWidth: 460, lineHeight: 1.5 }}>Offerroom maps who you already know, then finds warm paths into your targets. It never messages anyone without your approval.</p>
        </div>
        {phase === "connect" ? (
          <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {NET_ACCOUNTS.map(a => (
              <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 13, padding: 14, background: "#fff", border: "1px solid var(--ink-100)", borderRadius: 10 }}>
                <span style={{ width: 38, height: 38, borderRadius: 9, background: TONES[a.tone].tint, color: TONES[a.tone].text, display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name={a.icon} size={18}/></span>
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13.5, fontWeight: 600 }}>{a.label}</div><div style={{ fontSize: 12, color: "var(--fg-2)" }}>{a.sub}</div></div>
                {accountsSynced ? <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--sage-text)", fontWeight: 600 }}><Icon name="check" size={14}/>Connected</span> : <Button variant="secondary" size="sm" icon="link">Connect</Button>}
              </div>
            ))}
            <div style={{ display: "flex", justifyContent: "center", marginTop: 6 }}>
              <Button variant="primary" size="md" icon="route" onClick={() => setPhase("syncing")}>{firstRun ? "Sync my network" : "Re-sync now"}</Button>
            </div>
          </div>
        ) : (
          <Panel pad={26} className="cad-rise">
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}><span className="cad-pulse-dot"/><span style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 500 }}>Mapping your network</span></div>
            <div style={{ height: 6, borderRadius: 999, background: "var(--paper-sunken)", marginTop: 16, overflow: "hidden" }}><div style={{ height: "100%", width: pct + "%", background: "#8C1515", borderRadius: 999, transition: "width 230ms" }}/></div>
            <div style={{ marginTop: 15, display: "flex", flexDirection: "column", gap: 8 }}>
              {lines.map((l, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13, color: i <= active ? "var(--fg-1)" : "var(--fg-3)" }}>
                  <span style={{ width: 16, height: 16, borderRadius: 999, display: "grid", placeItems: "center", background: i < active ? "#5A7150" : "transparent", color: "#fff", border: i < active ? "none" : "1.5px solid var(--ink-100)" }}>{i < active && <Icon name="check" size={10}/>}</span>{l}
                </div>
              ))}
            </div>
          </Panel>
        )}
      </div>
    </div>
  );
}

const iconBtn = { width: 28, height: 28, borderRadius: 7, border: "1px solid var(--ink-100)", background: "#fff", cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-2)", flexShrink: 0 };
const modalScrim = { position: "fixed", inset: 0, zIndex: 120, background: "rgba(31,27,22,0.32)", display: "grid", placeItems: "center", padding: 24 };

Object.assign(window, { DetailPanel, ComposeModal, OutreachDrawer, ThreadDetail, NoPathPanel, UpsellModal, SyncOverlay, primaryOf, actionLabel });
