/* Settings — admin control surface (profile + team + roles + notification routing
   + house rules + integrations + preview-as). Every member has a full profile:
   name, handle, phone, password (simulated — only a flag is stored, never the
   value), company details and social sign-in connections. Non-admins get their
   own profile + notification prefs; everything else is admin-only. */
(function () {
  const S = window.CroprStore;
  const D = window.CROPR_DATA;

  const Check = ({ on, onChange, color, disabled }) => (
    <button disabled={disabled} onClick={() => !disabled && onChange(!on)} style={{ width: 22, height: 22, borderRadius: 6, flex: "none", cursor: disabled ? "default" : "pointer",
      border: `1.5px solid ${on ? (color || "var(--accent)") : "var(--border-strong)"}`, background: on ? (color || "var(--accent)") : "transparent",
      display: "grid", placeItems: "center", transition: "all 120ms", opacity: disabled ? 0.5 : 1 }}>{on && <Icon name="check" size={14} color="#fff" />}</button>
  );
  const Switch = ({ on, onChange }) => (
    <button onClick={() => onChange(!on)} style={{ width: 42, height: 24, borderRadius: 999, border: 0, cursor: "pointer", padding: 3, background: on ? "var(--success)" : "var(--border-strong)", display: "flex", justifyContent: on ? "flex-end" : "flex-start", transition: "background 160ms" }}><span style={{ width: 18, height: 18, borderRadius: 999, background: "#fff", boxShadow: "var(--shadow-sm)" }} /></button>
  );
  const roleName = (id) => (S.getRoles().find((r) => r.id === id) || {}).name || id;

  const fieldStyle = { width: "100%", boxSizing: "border-box", fontFamily: "inherit", fontSize: 13.5, color: "var(--fg1)", background: "var(--surface)", border: "1px solid var(--border-strong)", borderRadius: 10, padding: "9px 11px", outline: "none", transition: "border-color 140ms" };
  // commits on blur — used where a change has side effects (renaming) or we don't
  // want a store write per keystroke.
  function CommitInput({ value, onCommit, placeholder, prefix }) {
    const [v, setV] = React.useState(value);
    React.useEffect(() => setV(value), [value]);
    return <input value={v} placeholder={placeholder} onChange={(e) => setV(e.target.value)} onBlur={() => { if (v !== value) onCommit(v); }}
      onFocus={(e) => (e.target.style.borderColor = "var(--accent)")} onMouseLeave={(e) => {}} style={{ ...fieldStyle }} />;
  }
  const Label = ({ children }) => <span style={{ fontSize: 12, fontWeight: 600, color: "var(--fg2)", display: "block", marginBottom: 6 }}>{children}</span>;

  // ---------------- Shared: full profile editor --------------------------
  function ProfileEditor({ m, canEditRole, onToast, self }) {
    const roles = S.getRoles();
    const c = m.company || {};
    const ac = S.getActiveClient(); // when a client account is active, the company IS the client
    const social = m.social || {};
    const [pw1, setPw1] = React.useState(""); const [pw2, setPw2] = React.useState("");
    const savePw = () => {
      if (pw1.length < 6) { onToast("Password must be at least 6 characters", "error"); return; }
      if (pw1 !== pw2) { onToast("Passwords don't match", "error"); return; }
      S.setMemberPassword(m.id); setPw1(""); setPw2(""); onToast("Password updated");
    };
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        {/* identity */}
        <Card pad={20}>
          <SectionTitle icon="user">Profile</SectionTitle>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
            {window.memberAvatar(m.name, 52)}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 17, fontWeight: 700 }}>{m.fullName || m.name}</div>
              <div style={{ fontSize: 12.5, color: "var(--fg3)", fontFamily: "var(--font-mono)" }}>{m.handle || ("@" + m.name.toLowerCase())}</div>
            </div>
            <Badge color="var(--accent)" bg="var(--accent-weak)" dot>{roleName(m.roleId)}</Badge>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="profile-grid">
            <div><Label>Full name</Label><input defaultValue={m.fullName || ""} placeholder="Full name" onBlur={(e) => S.updateMember(m.id, { fullName: e.target.value })} style={fieldStyle} /></div>
            <div><Label>Display name</Label><CommitInput value={m.name} placeholder="Display name" onCommit={(v) => { if (!S.renameMember(m.id, v)) onToast("That display name is taken", "error"); else onToast("Name updated"); }} /></div>
            <div><Label>Handle</Label><input defaultValue={m.handle || ""} placeholder="@handle" onBlur={(e) => S.updateMember(m.id, { handle: e.target.value })} style={fieldStyle} /></div>
            <div><Label>Email</Label><input defaultValue={m.email || ""} placeholder="email@leap.app" onBlur={(e) => S.updateMember(m.id, { email: e.target.value })} style={fieldStyle} /></div>
            <div><Label>Phone <span style={{ color: "var(--fg4)", fontWeight: 500 }}>· optional</span></Label><input defaultValue={m.phone || ""} placeholder="+1 555 000 0000" onBlur={(e) => S.updateMember(m.id, { phone: e.target.value })} style={fieldStyle} /></div>
            <div><Label>Workspace role</Label>
              {canEditRole
                ? <Select value={m.roleId} onChange={(v) => S.updateMember(m.id, { roleId: v })} options={roles.map((r) => ({ value: r.id, label: r.name }))} />
                : <input value={roleName(m.roleId)} disabled style={{ ...fieldStyle, color: "var(--fg3)", background: "var(--bg-muted)" }} />}
            </div>
          </div>
          {!canEditRole && <div style={{ fontSize: 11.5, color: "var(--fg4)", marginTop: 10, display: "flex", gap: 6, alignItems: "center" }}><Icon name="lock" size={13} color="var(--fg4)" />Your workspace role is managed by an admin.</div>}
        </Card>

        {/* password */}
        <Card pad={20}>
          <SectionTitle icon="key-round">Password</SectionTitle>
          <div style={{ fontSize: 12, color: "var(--fg3)", marginBottom: 12 }}>{m.passwordSet ? "A password is set." : "No password set yet."}{m.passwordUpdatedAt ? ` Last changed ${new Date(m.passwordUpdatedAt).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })}.` : ""}</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, maxWidth: 460 }} className="profile-grid">
            <div><Label>New password</Label><input type="password" value={pw1} autoComplete="new-password" onChange={(e) => setPw1(e.target.value)} placeholder="••••••••" style={fieldStyle} /></div>
            <div><Label>Confirm</Label><input type="password" value={pw2} autoComplete="new-password" onChange={(e) => setPw2(e.target.value)} placeholder="••••••••" style={fieldStyle} /></div>
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: 12 }}>
            <Button variant="primary" icon="check" onClick={savePw}>{m.passwordSet ? "Change password" : "Set password"}</Button>
            <span style={{ fontSize: 11.5, color: "var(--fg4)", display: "flex", gap: 6, alignItems: "center" }}><Icon name="shield" size={13} color="var(--fg4)" />Simulated — the value is never stored in this demo.</span>
          </div>
        </Card>

        {/* company — the active client account when one is selected, else your own */}
        <Card pad={20}>
          <SectionTitle icon="building-2">Company{ac ? " · client account" : ""}</SectionTitle>
          {ac ? (
            <React.Fragment>
              <div style={{ fontSize: 12, color: "var(--fg3)", marginBottom: 10 }}>You're working in the <b>{ac.name}</b> account — this is the client's company. Your identity above stays the same across all clients.</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="profile-grid">
                <div><Label>Company (client)</Label><input key={ac.id + "n"} defaultValue={ac.name} placeholder="Client company" onBlur={(e) => S.updateClient(ac.id, { name: e.target.value })} style={fieldStyle} /></div>
                <div><Label>Your title here</Label><input defaultValue={c.jobTitle || ""} placeholder="e.g. Account manager" onBlur={(e) => S.updateMemberCompany(m.id, { jobTitle: e.target.value })} style={fieldStyle} /></div>
                <div><Label>Website</Label><input key={ac.id + "w"} defaultValue={ac.website || ""} placeholder="example.com" onBlur={(e) => S.updateClient(ac.id, { website: e.target.value })} style={fieldStyle} /></div>
                <div><Label>Location</Label><input key={ac.id + "l"} defaultValue={ac.location || ""} placeholder="e.g. London, UK" onBlur={(e) => S.updateClient(ac.id, { location: e.target.value })} style={fieldStyle} /></div>
              </div>
            </React.Fragment>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="profile-grid">
              <div><Label>Company</Label><input defaultValue={c.name || ""} placeholder="Company name" onBlur={(e) => S.updateMemberCompany(m.id, { name: e.target.value })} style={fieldStyle} /></div>
              <div><Label>Job title / role</Label><input defaultValue={c.jobTitle || ""} placeholder="e.g. Social Manager" onBlur={(e) => S.updateMemberCompany(m.id, { jobTitle: e.target.value })} style={fieldStyle} /></div>
              <div><Label>Department</Label><input defaultValue={c.department || ""} placeholder="e.g. Marketing" onBlur={(e) => S.updateMemberCompany(m.id, { department: e.target.value })} style={fieldStyle} /></div>
              <div><Label>Location</Label><input defaultValue={c.location || ""} placeholder="e.g. London, UK" onBlur={(e) => S.updateMemberCompany(m.id, { location: e.target.value })} style={fieldStyle} /></div>
            </div>
          )}
        </Card>

        {/* published wizard profile — saved below the company data */}
        {self && S.getMyWizard() && <WizardPublishedCard onToast={onToast} />}

        {/* social sign-in */}
        <Card pad={20}>
          <SectionTitle icon="link">Social sign-in</SectionTitle>
          <div style={{ fontSize: 12, color: "var(--fg3)", marginBottom: 10 }}>Connect an account to sign in with it. Simulated — wires to OAuth in production.</div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {D.SOCIAL_LOGINS.map((p) => {
              const on = !!social[p.id];
              return (
                <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 0", borderBottom: "1px solid var(--border)" }}>
                  <PlatformLogo platform={p.platform} size={28} style={{ borderRadius: 7 }} />
                  <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1 }}>{p.label}{on && <span style={{ fontSize: 11.5, color: "#0E8A50", fontWeight: 600, marginLeft: 8 }}>· connected</span>}</span>
                  <Button size="sm" variant={on ? "secondary" : "primary"} icon={on ? "unplug" : "plug"} onClick={() => S.toggleMemberSocial(m.id, p.id, !on)}>{on ? "Disconnect" : "Connect"}</Button>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    );
  }

  // ---------------- Become a Wizard (in the profile, below Company) -------
  const svcMeta = (id) => (D.WIZARD_SERVICES || []).find((s) => s.id === id) || { label: id, icon: "tag" };
  const readImg = (f, cb) => { if (!f) return; const r = new FileReader(); r.onload = () => cb({ url: r.result, kind: (f.type || "").startsWith("video") ? "video" : "image", name: f.name.replace(/\.[^.]+$/, "") }); r.readAsDataURL(f); };
  const PROMO_BODY = "Book me on @Leap. I'm a Social Media Wizard on Leap — the smarter social media management tool. Join me now and make a Leap.";

  function BecomeWizardModal({ onClose, onToast }) {
    const me = S.getMyWizard();
    const [headline, setHeadline] = React.useState(me ? me.headline : "");
    const [bio, setBio] = React.useState(me ? me.bio : "");
    const [location, setLocation] = React.useState(me ? me.location : "");
    const [specs, setSpecs] = React.useState(me ? me.specialties : []);
    const [responseTime, setResponseTime] = React.useState(me ? me.responseTime : "within a day");
    const [fromPrice, setFromPrice] = React.useState(me ? me.fromPrice : "");
    const [showcases, setShowcases] = React.useState(me ? (me.showcases || []) : []);
    const toggleSpec = (id) => setSpecs((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
    const publish = () => {
      if (!headline.trim()) { onToast("Add a headline first", "error"); return; }
      const wasNew = !S.getMyWizard();
      S.publishExpert({ headline, bio, location, specialties: specs, responseTime, fromPrice: +fromPrice || 0, showcases });
      if (wasNew) {
        const first = showcases[0];
        S.create({ title: "I'm a Wizard on Leap", status: "in_draft", channels: ["x_cropr"], proofMarked: true, tags: ["wizard"],
          content: [{ channel: "x_cropr", format: "single", body: PROMO_BODY, media: first ? [{ kind: first.kind, url: first.url, altText: "Social Media Wizard on Leap", status: "ready" }] : [] }] });
        onToast("You're a Wizard 🎉 A promo post was drafted on your channels — find it in Posts.");
      } else onToast("Wizard profile updated");
      onClose();
    };
    return (
      <Modal open title={me ? "Edit your Wizard profile" : "Become a Wizard"} subtitle="Publish your profile, references and services" onClose={onClose} width={620}
        footer={<React.Fragment><Button variant="ghost" onClick={onClose}>Cancel</Button><Button variant="primary" icon="wand-2" onClick={publish}>{me ? "Save profile" : "Publish profile"}</Button></React.Fragment>}>
        <div style={{ marginBottom: 12 }}><Label>Headline</Label><input value={headline} onChange={(e) => setHeadline(e.target.value)} placeholder="e.g. Short-form video that converts" style={fieldStyle} /></div>
        <div style={{ marginBottom: 12 }}><Label>Bio</Label><textarea value={bio} onChange={(e) => setBio(e.target.value)} rows={3} placeholder="Who you help and how." style={{ ...fieldStyle, resize: "vertical", lineHeight: 1.5 }} /></div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12 }} className="profile-grid">
          <div><Label>Location</Label><input value={location} onChange={(e) => setLocation(e.target.value)} placeholder="e.g. Remote · London, UK" style={fieldStyle} /></div>
          <div><Label>Response time</Label><Select value={responseTime} onChange={setResponseTime} options={["within 1 hour", "within 2 hours", "same day", "within a day", "within 2 days"].map((x) => ({ value: x, label: x }))} /></div>
          <div><Label>Starting price ($)</Label><input type="number" value={fromPrice} onChange={(e) => setFromPrice(e.target.value)} placeholder="e.g. 150" style={fieldStyle} /></div>
        </div>
        <Label>What you offer</Label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 14 }}>
          {D.WIZARD_SERVICES.map((s) => { const on = specs.includes(s.id); return <button key={s.id} onClick={() => toggleSpec(s.id)} style={{ display: "inline-flex", alignItems: "center", gap: 5, border: `1px solid ${on ? "var(--leap-teal)" : "var(--border-strong)"}`, background: on ? "var(--accent-weak)" : "transparent", color: on ? "var(--accent)" : "var(--fg2)", borderRadius: 999, padding: "4px 10px", fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}><Icon name={s.icon} size={12} color={on ? "var(--accent)" : "var(--fg3)"} />{s.label}</button>; })}
        </div>
        <Label>References &amp; showcases</Label>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center", marginBottom: 8 }}>
          {showcases.map((s, i) => (
            <div key={i} style={{ position: "relative", width: 84, height: 84, borderRadius: 12, overflow: "hidden", border: "1px solid var(--border)" }}>
              {s.kind === "video" ? <video src={s.url} muted style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <img src={s.url} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />}
              <button onClick={() => setShowcases(showcases.filter((_, j) => j !== i))} style={{ position: "absolute", top: 3, right: 3, width: 18, height: 18, borderRadius: 999, border: 0, background: "rgba(11,59,66,.7)", cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="x" size={11} color="#fff" /></button>
            </div>
          ))}
          <label style={{ width: 84, height: 84, borderRadius: 12, border: "1.5px dashed var(--border-strong)", display: "grid", placeItems: "center", cursor: "pointer" }}>
            <Icon name="plus" size={20} color="var(--fg4)" />
            <input type="file" accept="image/*,video/*" multiple style={{ display: "none" }} onChange={(e) => { [...(e.target.files || [])].forEach((f) => readImg(f, (m) => setShowcases((a) => [...a, m]))); e.target.value = ""; }} />
          </label>
        </div>
        <div style={{ fontSize: 11.5, color: "var(--fg4)", marginTop: 6, display: "flex", gap: 6, alignItems: "center" }}><Icon name="megaphone" size={13} color="var(--accent)" />Publishing drafts a post on your channels announcing you're a Wizard on Leap.</div>
      </Modal>
    );
  }

  function BecomeWizardBox({ onToast }) {
    const [modal, setModal] = React.useState(false);
    return (
      <React.Fragment>
        <Card pad={22} style={{ border: 0, color: "#fff", position: "relative", overflow: "hidden", background: "linear-gradient(140deg,#0B3B42 0%,#0E6B78 52%,#0EA5B7 100%)" }}>
          <div style={{ position: "absolute", inset: 0, background: "radial-gradient(circle at 1px 1px, rgba(255,255,255,.14) 1px, transparent 0)", backgroundSize: "20px 20px", opacity: .5, pointerEvents: "none" }} />
          <div style={{ position: "relative" }}>
            <span style={{ width: 46, height: 46, borderRadius: 13, background: "rgba(255,255,255,.18)", display: "grid", placeItems: "center", marginBottom: 12 }}><Icon name="wand-2" size={24} color="#fff" /></span>
            <div style={{ fontSize: 18, fontWeight: 700, fontFamily: "var(--font-display)" }}>Become a Wizard</div>
            <div style={{ fontSize: 13, opacity: .95, lineHeight: 1.55, margin: "6px 0 14px" }}>List your services, share free content and get booked by other Leap users. It's free to publish.</div>
            <ul style={{ margin: "0 0 16px", paddingLeft: 18, fontSize: 12.5, lineHeight: 1.7, opacity: .95 }}>
              <li>A profile with references &amp; showcases</li>
              <li>Bookable services, per job</li>
              <li>Publish free tips &amp; videos</li>
            </ul>
            <Button variant="secondary" icon="wand-2" full onClick={() => setModal(true)}>Set up my profile</Button>
          </div>
        </Card>
        {modal && <BecomeWizardModal onClose={() => setModal(false)} onToast={onToast} />}
      </React.Fragment>
    );
  }

  function WizardPublishedCard({ onToast }) {
    const me = S.getMyWizard();
    const [modal, setModal] = React.useState(false);
    const [off, setOff] = React.useState({ title: "", price: "", unit: "project", duration: "", desc: "" });
    const [con, setCon] = React.useState({ type: "tip", title: "", body: "" });
    if (!me) return null;
    return (
      <Card pad={20}>
        <SectionTitle icon="wand-2" right={<div style={{ display: "flex", gap: 6 }}><Button size="sm" variant="secondary" icon="pencil" onClick={() => setModal(true)}>Edit</Button><Button size="sm" variant="danger" icon="eye-off" onClick={() => { if (confirm("Unpublish your Wizard profile?")) { S.unpublishExpert(); onToast("Profile unpublished"); } }}>Unpublish</Button></div>}>Wizard profile</SectionTitle>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
          <span style={{ width: 42, height: 42, borderRadius: 11, background: me.color, color: "#fff", display: "grid", placeItems: "center", fontSize: 16, fontWeight: 800, flex: "none" }}>{me.name.slice(0, 1).toUpperCase()}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 700 }}>{me.headline || "Add a headline"}</div>
            <div style={{ fontSize: 12, color: "var(--fg3)" }}>{me.rating ? me.rating.toFixed(1) + "★ · " + me.jobs + " jobs · " : ""}Responds {me.responseTime}{me.fromPrice ? " · from $" + me.fromPrice : ""}</div>
          </div>
          <Badge color="#0E8A50" bg="var(--success-bg)" dot>Live</Badge>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 5, marginBottom: 14 }}>
          {(me.specialties || []).map((s) => <span key={s} style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11, fontWeight: 600, color: "var(--fg2)", background: "var(--bg-muted)", padding: "3px 8px", borderRadius: 999 }}><Icon name={svcMeta(s).icon} size={11} color="var(--fg3)" />{svcMeta(s).label}</span>)}
        </div>

        <div style={{ fontSize: 12, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em", margin: "6px 0 8px" }}>Services</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 10 }}>
          {(me.offerings || []).map((o) => (
            <div key={o.id} style={{ display: "flex", gap: 10, alignItems: "center", padding: "9px 12px", border: "1px solid var(--border)", borderRadius: 12 }}>
              <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 700 }}>{o.title}</div><div style={{ fontSize: 11.5, color: "var(--fg3)" }}>${o.price} / {o.unit}{o.duration ? " · " + o.duration : ""}</div></div>
              <button onClick={() => S.removeMyOffering(o.id)} style={{ border: 0, background: "none", cursor: "pointer" }}><Icon name="trash-2" size={15} color="var(--fg3)" /></button>
            </div>
          ))}
          {!(me.offerings || []).length && <div style={{ fontSize: 12, color: "var(--fg4)" }}>No services yet — add one below.</div>}
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 16 }}>
          <input value={off.title} onChange={(e) => setOff({ ...off, title: e.target.value })} placeholder="Service title" style={{ ...fieldStyle, flex: 1, minWidth: 140 }} />
          <input type="number" value={off.price} onChange={(e) => setOff({ ...off, price: e.target.value })} placeholder="$" style={{ ...fieldStyle, width: 80 }} />
          <Select value={off.unit} onChange={(v) => setOff({ ...off, unit: v })} options={["project", "hour", "day", "month", "post", "campaign"].map((u) => ({ value: u, label: "/ " + u }))} style={{ width: 110 }} />
          <Button variant="secondary" icon="plus" onClick={() => { if (!off.title.trim()) { onToast("Add a title", "error"); return; } S.addMyOffering(off); setOff({ title: "", price: "", unit: "project", duration: "", desc: "" }); onToast("Service added"); }}>Add</Button>
        </div>

        <div style={{ fontSize: 12, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em", margin: "6px 0 8px" }}>Free content</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 10 }}>
          {(me.content || []).map((c) => (
            <div key={c.id} style={{ display: "flex", gap: 10, alignItems: "center", padding: "9px 12px", border: "1px solid var(--border)", borderRadius: 12 }}>
              <Icon name={(D.WIZARD_CONTENT_TYPES.find((t) => t.id === c.type) || {}).icon || "file-text"} size={15} color="var(--fg3)" />
              <span style={{ fontSize: 13, fontWeight: 600, flex: 1 }}>{c.title}</span>
              <button onClick={() => S.removeMyContent(c.id)} style={{ border: 0, background: "none", cursor: "pointer" }}><Icon name="trash-2" size={15} color="var(--fg3)" /></button>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          <Select value={con.type} onChange={(v) => setCon({ ...con, type: v })} options={D.WIZARD_CONTENT_TYPES.map((t) => ({ value: t.id, label: t.label }))} style={{ width: 130 }} />
          <input value={con.title} onChange={(e) => setCon({ ...con, title: e.target.value })} placeholder="Title" style={{ ...fieldStyle, flex: 1, minWidth: 120 }} />
          <input value={con.body} onChange={(e) => setCon({ ...con, body: e.target.value })} placeholder="The tip in a sentence" style={{ ...fieldStyle, flex: 1, minWidth: 140 }} />
          <Button variant="secondary" icon="plus" onClick={() => { if (!con.title.trim()) { onToast("Add a title", "error"); return; } S.addMyContent(con); setCon({ type: "tip", title: "", body: "" }); onToast("Published to Discover"); }}>Publish</Button>
        </div>
        {modal && <BecomeWizardModal onClose={() => setModal(false)} onToast={onToast} />}
      </Card>
    );
  }

  // Real authenticated teammates (live): invite by email → find-or-create the
  // real user + membership; they join with their own login. Distinct from the
  // demo persona roster below.
  function RealTeam({ onToast }) {
    const live = !!(window.LeapAPI && window.LeapAPI.configured());
    const org = () => { try { return window.LeapGate && window.LeapGate.orgId ? window.LeapGate.orgId() : null; } catch (e) { return null; } };
    const [members, setMembers] = React.useState(null);
    const [email, setEmail] = React.useState("");
    const [role, setRole] = React.useState("editor");
    const [busy, setBusy] = React.useState(false);
    const ROLE_OPTS = [{ value: "admin", label: "Admin" }, { value: "editor", label: "Editor" }, { value: "viewer", label: "Viewer" }];
    const load = React.useCallback(async () => {
      const o = org(); if (!live || !o) return;
      try { const r = await window.LeapAPI.members(o); setMembers((r && r.members) || []); } catch (e) { setMembers([]); }
    }, [live]);
    React.useEffect(() => { load(); }, [load]);
    if (!live) return null;
    const invite = async () => {
      const o = org(); if (!o) return;
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) { onToast("Enter a valid email", "error"); return; }
      setBusy(true);
      try {
        const r = await window.LeapAPI.inviteMember(o, email.trim(), role);
        onToast(r && r.alreadyExisted ? "Added existing user to the team" : "Invite sent — they join when they sign in");
        setEmail(""); await load();
      } catch (e) { onToast((e && e.message) || "Invite failed", "error"); }
      finally { setBusy(false); }
    };
    const remove = async (m) => {
      const o = org(); if (!o) return;
      if (!confirm("Remove " + (m.name || m.email) + " from the team?")) return;
      try { await window.LeapAPI.removeMemberByUser(o, m.userId); onToast("Member removed"); await load(); }
      catch (e) { onToast((e && e.message) || "Remove failed", "error"); }
    };
    return (
      <Card pad={16} style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 4, display: "flex", alignItems: "center", gap: 6 }}><Icon name="users" size={15} color="var(--accent)" />Teammates · real accounts</div>
        <div style={{ fontSize: 11.5, color: "var(--fg3)", marginBottom: 12 }}>Invite by email — they join with their own login. Access is tied to their real account.</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 12 }}>
          {members === null && <div style={{ fontSize: 12, color: "var(--fg3)" }}>Loading…</div>}
          {members && members.length === 0 && <div style={{ fontSize: 12, color: "var(--fg3)" }}>No teammates yet.</div>}
          {(members || []).map((m) => (
            <div key={m.userId} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 10, background: "var(--bg-subtle)" }}>
              {window.memberAvatar(m.name, 28)}
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}>{m.name}{m.pending && <Badge color="#B25E09" bg="var(--warning-bg)" dot>Pending</Badge>}</div>
                <div style={{ fontSize: 11, color: "var(--fg3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.email || "—"}</div>
              </div>
              <Badge color="var(--accent)" bg="var(--accent-weak)">{m.role}</Badge>
              {m.role !== "owner" && <button title="Remove" onClick={() => remove(m)} style={{ border: 0, background: "none", cursor: "pointer" }}><Icon name="user-minus" size={16} color="var(--fg3)" /></button>}
            </div>
          ))}
        </div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center" }}>
          <TextInput value={email} onChange={setEmail} placeholder="teammate@email.com" style={{ width: 240 }} onKeyDown={(e) => { if (e.key === "Enter") invite(); }} />
          <Select value={role} onChange={setRole} options={ROLE_OPTS} style={{ width: 130 }} />
          <Button variant="primary" icon="mail" disabled={busy} onClick={invite}>{busy ? "Inviting…" : "Invite"}</Button>
        </div>
      </Card>
    );
  }

  // ---------------- Admin: People (team management + profiles) ------------
  function People({ team, roles, onToast }) {
    const [name, setName] = React.useState("");
    const [email, setEmail] = React.useState("");
    const [roleId, setRoleId] = React.useState("creator");
    const [openId, setOpenId] = React.useState(null);
    const ac = S.getActiveClient(); // People are scoped to the active client account
    const roleOpts = roles.map((r) => ({ value: r.id, label: r.name }));
    const add = () => { if (!name.trim()) { onToast("Enter a name", "error"); return; } const id = S.addMember(name, email, roleId); if (ac && id) S.assignClientUser(ac.id, id, true); setName(""); setEmail(""); onToast(ac ? `Added to ${ac.name}` : "Member added"); };
    const removeMember = (m) => {
      if (ac) { if (confirm(`Remove ${m.name} from ${ac.name}?`)) { S.assignClientUser(ac.id, m.id, false); onToast("Removed from client"); } }
      else if (confirm("Remove " + m.name + " from the team?")) { S.removeMember(m.id); onToast("Member removed"); }
    };
    return (
      <div>
        <RealTeam onToast={onToast} />
        <Card pad={0} style={{ marginBottom: 14 }}>
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.5fr) minmax(0,1.6fr) 150px 84px", gap: 12, padding: "10px 18px", background: "var(--bg-subtle)", borderBottom: "1px solid var(--border)", borderRadius: "16px 16px 0 0" }}>
            {["Member", "Email", "Role", ""].map((h, i) => <span key={i} style={{ fontSize: 10.5, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em" }}>{h}</span>)}
          </div>
          {team.map((m) => (
            <React.Fragment key={m.id}>
              <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.5fr) minmax(0,1.6fr) 150px 84px", gap: 12, padding: "11px 18px", borderBottom: "1px solid var(--border)", alignItems: "center" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>{window.memberAvatar(m.name, 30)}<div style={{ minWidth: 0 }}><div style={{ fontSize: 13.5, fontWeight: 700 }}>{m.name}</div><div style={{ fontSize: 11, color: "var(--fg3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.company && m.company.jobTitle ? m.company.jobTitle : m.handle}</div></div></div>
                <div style={{ fontSize: 12.5, color: "var(--fg2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.email || "—"}</div>
                <Select value={m.roleId} onChange={(v) => S.updateMember(m.id, { roleId: v })} options={roleOpts} />
                <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                  <button title="Edit profile" onClick={() => setOpenId(openId === m.id ? null : m.id)} style={{ border: 0, background: "none", cursor: "pointer" }}><Icon name={openId === m.id ? "chevron-up" : "pencil"} size={16} color="var(--fg3)" /></button>
                  {!(m.roleId === "admin" && team.filter((t) => t.roleId === "admin").length <= 1) &&
                    <button title={ac ? "Remove from client" : "Remove"} onClick={() => removeMember(m)} style={{ border: 0, background: "none", cursor: "pointer" }}><Icon name={ac ? "user-minus" : "trash-2"} size={16} color="var(--fg3)" /></button>}
                </div>
              </div>
              {openId === m.id && <div style={{ padding: "14px 18px 18px", background: "var(--bg-subtle)", borderBottom: "1px solid var(--border)" }}><ProfileEditor m={m} canEditRole={true} onToast={onToast} /></div>}
            </React.Fragment>
          ))}
        </Card>
        <Card pad={16}>
          <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 10 }}>{ac ? `Add someone to ${ac.name}` : "Add a team member"}</div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center" }}>
            <TextInput value={name} onChange={setName} placeholder="Name" style={{ width: 160 }} />
            <TextInput value={email} onChange={setEmail} placeholder="email@leap.app" style={{ width: 220 }} />
            <Select value={roleId} onChange={setRoleId} options={roleOpts} style={{ width: 160 }} />
            <Button variant="primary" icon="user-plus" onClick={add}>Add member</Button>
          </div>
        </Card>
      </div>
    );
  }

  function RolesRights({ roles, onToast }) {
    return (
      <div>
        <div style={{ overflowX: "auto" }}>
          <Card pad={0} style={{ minWidth: 720 }}>
            <div style={{ display: "grid", gridTemplateColumns: `180px repeat(${D.ACTIONS.length}, 1fr) 40px`, gap: 4, padding: "10px 14px", background: "var(--bg-subtle)", borderBottom: "1px solid var(--border)", borderRadius: "16px 16px 0 0" }}>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em" }}>Role</span>
              {D.ACTIONS.map((a) => <span key={a.id} title={a.label} style={{ fontSize: 10, fontWeight: 700, color: "var(--fg3)", textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 3 }}><Icon name={a.icon} size={15} color="var(--fg3)" />{a.label.split(" ")[0]}</span>)}
              <span />
            </div>
            {roles.map((role) => (
              <div key={role.id} style={{ display: "grid", gridTemplateColumns: `180px repeat(${D.ACTIONS.length}, 1fr) 40px`, gap: 4, padding: "10px 14px", borderBottom: "1px solid var(--border)", alignItems: "center" }}>
                <input value={role.name} onChange={(e) => S.updateRole(role.id, { name: e.target.value })} disabled={role.id === "admin"} style={{ fontFamily: "inherit", fontSize: 13, fontWeight: 700, border: "1px solid transparent", background: "transparent", color: "var(--fg1)", padding: "4px 6px", borderRadius: 6, minWidth: 0 }} onFocus={(e) => e.target.style.borderColor = "var(--border-strong)"} onBlur={(e) => e.target.style.borderColor = "transparent"} />
                {D.ACTIONS.map((a) => <div key={a.id} style={{ display: "grid", placeItems: "center" }}><Check on={role.rights.includes(a.id)} disabled={role.id === "admin"} onChange={() => S.toggleRoleRight(role.id, a.id)} /></div>)}
                <div style={{ display: "grid", placeItems: "center" }}>{role.id !== "admin" && <button onClick={() => { if (confirm("Delete role “" + role.name + "”? Members on it move to Creator.")) { S.removeRole(role.id); onToast("Role deleted"); } }} style={{ border: 0, background: "none", cursor: "pointer" }}><Icon name="trash-2" size={15} color="var(--fg3)" /></button>}</div>
              </div>
            ))}
          </Card>
        </div>
        <div style={{ marginTop: 12 }}><Button variant="secondary" icon="plus" onClick={() => { const n = prompt("New role name:"); if (n && n.trim()) { S.addRole(n.trim()); onToast("Role added — set its rights"); } }}>Add role</Button></div>
      </div>
    );
  }

  function NotifRouting({ team, settings, onToast }) {
    return (
      <div>
        <Card pad={18} style={{ marginBottom: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ width: 40, height: 40, borderRadius: 11, background: "var(--accent-weak)", display: "grid", placeItems: "center", flex: "none" }}><Icon name="mail" size={20} color="var(--accent)" /></span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700 }}>Email delivery</div>
              <div style={{ fontSize: 12, color: "var(--fg3)" }}>Send notifications & reminders by email too (per-member toggle below). On by default. Simulated — wire an email/SMTP provider in production.</div>
            </div>
            <Switch on={settings.emailEnabled} onChange={(v) => { S.setNotifSettings({ emailEnabled: v }); onToast("Email delivery " + (v ? "on" : "off")); }} />
          </div>
        </Card>
        <div style={{ overflowX: "auto" }}>
          <Card pad={0} style={{ minWidth: 640 }}>
            <div style={{ display: "grid", gridTemplateColumns: `160px repeat(${D.NOTIF_CATEGORIES.length}, 1fr) 90px`, gap: 6, padding: "10px 16px", background: "var(--bg-subtle)", borderBottom: "1px solid var(--border)", borderRadius: "16px 16px 0 0", alignItems: "end" }}>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em" }}>Member</span>
              {D.NOTIF_CATEGORIES.map((c) => <span key={c.id} title={c.label} style={{ fontSize: 10, fontWeight: 700, color: "var(--fg3)", textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 3 }}><Icon name={c.icon} size={15} color="var(--fg3)" />{c.label.split(" ")[0]}</span>)}
              <span style={{ fontSize: 10, fontWeight: 700, color: "var(--fg3)", textAlign: "center" }}>Email</span>
            </div>
            {team.map((m) => (
              <div key={m.id} style={{ display: "grid", gridTemplateColumns: `160px repeat(${D.NOTIF_CATEGORIES.length}, 1fr) 90px`, gap: 6, padding: "11px 16px", borderBottom: "1px solid var(--border)", alignItems: "center" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>{window.memberAvatar(m.name, 26)}<span style={{ fontSize: 13, fontWeight: 700 }}>{m.name}</span></div>
                {D.NOTIF_CATEGORIES.map((c) => <div key={c.id} style={{ display: "grid", placeItems: "center" }}><Check on={!!(m.notify && m.notify[c.id])} onChange={(v) => S.updateMemberNotify(m.id, c.id, v)} /></div>)}
                <div style={{ display: "grid", placeItems: "center" }}><Check on={!!m.emailOn} color="var(--success)" onChange={(v) => S.updateMember(m.id, { emailOn: v })} /></div>
              </div>
            ))}
          </Card>
        </div>
        <div style={{ fontSize: 11.5, color: "var(--fg3)", marginTop: 10, display: "flex", gap: 6, alignItems: "center" }}><Icon name="info" size={14} color="var(--fg4)" />Task notifications route to the assigned person for that step; if no one is assigned, everyone whose role holds that right is notified.</div>
      </div>
    );
  }

  // ---------------- Admin: House rules editor ----------------------------
  function HouseRules({ onToast }) {
    const rules = S.getHouseRules();
    const [draft, setDraft] = React.useState("");
    return (
      <div style={{ maxWidth: 680 }}>
        <Card pad={20}>
          <SectionTitle icon="scroll-text">House rules</SectionTitle>
          <div style={{ fontSize: 12.5, color: "var(--fg3)", marginBottom: 14 }}>The content guidelines shown to everyone in the sidebar. Edit them to fit your team's standards.</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {rules.map((r, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 22, height: 22, borderRadius: 7, background: "var(--accent-weak)", color: "var(--accent)", display: "grid", placeItems: "center", flex: "none", fontSize: 11, fontWeight: 700 }}>{i + 1}</span>
                <input defaultValue={r} onBlur={(e) => S.updateHouseRule(i, e.target.value)} style={fieldStyle} />
                <button title="Remove" onClick={() => { S.removeHouseRule(i); onToast("Rule removed"); }} style={{ border: 0, background: "none", cursor: "pointer", flex: "none" }}><Icon name="trash-2" size={16} color="var(--fg3)" /></button>
              </div>
            ))}
            {rules.length === 0 && <div style={{ fontSize: 12.5, color: "var(--fg4)" }}>No rules yet — add your first below.</div>}
          </div>
          <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
            <TextInput value={draft} onChange={setDraft} placeholder="Add a house rule…" style={{ flex: 1 }} />
            <Button variant="primary" icon="plus" onClick={() => { if (draft.trim()) { S.addHouseRule(draft.trim()); setDraft(""); onToast("Rule added"); } }}>Add</Button>
          </div>
        </Card>
      </div>
    );
  }

  // ---------------- Admin: workflow editor -------------------------------
  // The pipeline stages that drive both the board columns and the post rail.
  // One flow per workspace; admins can rename, reorder, add and remove stages.
  function WorkflowEditor({ onToast }) {
    const [, force] = React.useReducer((x) => x + 1, 0);
    const stages = S.getWorkflow();
    const [draft, setDraft] = React.useState("");
    const colorOf = (key) => (window.CROPR_DATA.STATUS_MAP[key] || {}).color || "var(--fg4)";
    return (
      <div style={{ maxWidth: 680 }}>
        <Card pad={20}>
          <SectionTitle icon="git-branch">Workflow stages</SectionTitle>
          <div style={{ fontSize: 12.5, color: "var(--fg3)", marginBottom: 14 }}>The pipeline every post moves through. These are the columns on the board and the steps in each post's rail. For each stage you can pick a responsible person on the post itself — they're notified when a post reaches their stage.</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {stages.map((s, i) => (
              <div key={s.key} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 10, height: 10, borderRadius: 3, background: colorOf(s.key), flex: "none" }} />
                <span style={{ width: 22, textAlign: "center", flex: "none", fontSize: 11, fontWeight: 700, color: "var(--fg3)" }}>{i + 1}</span>
                <input defaultValue={s.name} key={s.key + ":" + s.name} onBlur={(e) => { const v = e.target.value.trim(); if (v && v !== s.name) { S.renameStage(s.key, v); onToast("Stage renamed"); } }} style={fieldStyle} />
                <button title="Move up" disabled={i === 0} onClick={() => { S.moveStage(s.key, -1); force(); }} style={{ border: 0, background: "none", cursor: i === 0 ? "default" : "pointer", opacity: i === 0 ? .3 : 1, flex: "none" }}><Icon name="chevron-up" size={16} color="var(--fg3)" /></button>
                <button title="Move down" disabled={i === stages.length - 1} onClick={() => { S.moveStage(s.key, 1); force(); }} style={{ border: 0, background: "none", cursor: i === stages.length - 1 ? "default" : "pointer", opacity: i === stages.length - 1 ? .3 : 1, flex: "none" }}><Icon name="chevron-down" size={16} color="var(--fg3)" /></button>
                <button title="Remove stage" disabled={stages.length <= 1} onClick={() => { if (confirm(`Remove the "${s.name}" stage? Posts in it will need to be moved.`)) { S.removeStage(s.key); onToast("Stage removed"); } }} style={{ border: 0, background: "none", cursor: stages.length <= 1 ? "default" : "pointer", opacity: stages.length <= 1 ? .3 : 1, flex: "none" }}><Icon name="trash-2" size={16} color="var(--fg3)" /></button>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
            <TextInput value={draft} onChange={setDraft} placeholder="Add a stage (e.g. Legal review)…" style={{ flex: 1 }} />
            <Button variant="primary" icon="plus" onClick={() => { if (draft.trim()) { S.addStage(draft.trim()); setDraft(""); onToast("Stage added"); } }}>Add</Button>
          </div>
        </Card>
      </div>
    );
  }

  // Read-only workflow view for non-admins.
  function WorkflowReadonly() {
    const stages = S.getWorkflow();
    const colorOf = (key) => (window.CROPR_DATA.STATUS_MAP[key] || {}).color || "var(--fg4)";
    return (
      <div style={{ maxWidth: 680 }}>
        <Card pad={20}>
          <SectionTitle icon="git-branch">Workflow stages</SectionTitle>
          <div style={{ fontSize: 12.5, color: "var(--fg3)", marginBottom: 14 }}>The pipeline every post moves through. Only a workspace admin can change these.</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {stages.map((s, i) => (
              <span key={s.key} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, padding: "4px 10px", borderRadius: 999, background: colorOf(s.key) + "18", color: colorOf(s.key) }}>
                <span style={{ width: 7, height: 7, borderRadius: 2, background: colorOf(s.key) }} />{s.name}
              </span>
            ))}
          </div>
        </Card>
      </div>
    );
  }

  // ---------------- Admin: post setup (intents + tones) ------------------
  // Editable option lists that feed the AI composer's Intent + Tone dropdowns.
  function OptionListEditor({ icon, title, blurb, items, onAdd, onRename, onRemove, placeholder, onToast }) {
    const [draft, setDraft] = React.useState("");
    return (
      <Card pad={20}>
        <SectionTitle icon={icon}>{title}</SectionTitle>
        <div style={{ fontSize: 12.5, color: "var(--fg3)", marginBottom: 14 }}>{blurb}</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {items.map((it) => (
            <div key={it.id} style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--bg-subtle)", border: "1px solid var(--border)", borderRadius: 999, padding: "4px 6px 4px 12px" }}>
              <input defaultValue={it.label} key={it.id + ":" + it.label} onBlur={(e) => { const v = e.target.value.trim(); if (v && v !== it.label) { onRename(it.id, v); onToast("Renamed"); } }}
                style={{ border: 0, background: "transparent", fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "var(--fg1)", outline: "none", width: Math.max(60, (it.label.length + 1) * 7.5) }} />
              <button title="Remove" onClick={() => { onRemove(it.id); onToast("Removed"); }} style={{ border: 0, background: "none", cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="x" size={14} color="var(--fg3)" /></button>
            </div>
          ))}
          {items.length === 0 && <div style={{ fontSize: 12.5, color: "var(--fg4)" }}>None yet — add your first below.</div>}
        </div>
        <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
          <TextInput value={draft} onChange={setDraft} placeholder={placeholder} style={{ flex: 1 }} />
          <Button variant="primary" icon="plus" onClick={() => { if (draft.trim()) { onAdd(draft.trim()); setDraft(""); onToast("Added"); } }}>Add</Button>
        </div>
      </Card>
    );
  }
  function PostSetup({ onToast }) {
    const [, force] = React.useReducer((x) => x + 1, 0);
    const refresh = () => force();
    return (
      <div style={{ maxWidth: 720, display: "flex", flexDirection: "column", gap: 16 }}>
        <Card pad={20} style={{ background: "var(--gradient-hero)", border: 0, color: "#fff" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}><Icon name="sliders-horizontal" size={18} color="#fff" /><span style={{ fontWeight: 700, fontSize: 14 }}>Post setup</span></div>
          <div style={{ fontSize: 13, lineHeight: 1.55, opacity: .95 }}>The Intent and Tone options here appear in the post composer and steer what the AI writes. Add your team's own or remove ones you don't use.</div>
        </Card>
        <OptionListEditor icon="target" title="Intents" onToast={(m) => { onToast(m); refresh(); }}
          blurb="What a post is trying to achieve — shown as the Intent dropdown on each post."
          items={S.getIntents()} placeholder="Add an intent (e.g. Educate, Recruit)…"
          onAdd={(n) => S.addIntent(n)} onRename={(id, n) => S.renameIntent(id, n)} onRemove={(id) => S.removeIntent(id)} />
        <OptionListEditor icon="mic" title="Tones" onToast={(m) => { onToast(m); refresh(); }}
          blurb="How a post should sound — shown as the Tone dropdown on each post."
          items={S.getTones()} placeholder="Add a tone (e.g. Bold, Warm)…"
          onAdd={(n) => S.addTone(n)} onRename={(id, n) => S.renameTone(id, n)} onRemove={(id) => S.removeTone(id)} />
      </div>
    );
  }

  // ---------------- Admin: brand & campaign brief ------------------------
  function BrandSettings({ onToast }) {
    const brand = S.getBrand();
    const taStyle = { ...fieldStyle, minHeight: 120, resize: "vertical", lineHeight: 1.5 };
    return (
      <div style={{ maxWidth: 720, display: "flex", flexDirection: "column", gap: 16 }}>
        <Card pad={20} style={{ background: "var(--gradient-hero)", border: 0, color: "#fff" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}><Icon name="sparkles" size={18} color="#fff" /><span style={{ fontWeight: 700, fontSize: 14 }}>Context for the AI</span></div>
          <div style={{ fontSize: 13, lineHeight: 1.55, opacity: .95 }}>The brand brief steers the campaign ideas the AI proposes; the brand voice sets the tone it writes posts in. The more specific you are, the more on-brand the output.</div>
        </Card>
        <Card pad={20}>
          <SectionTitle icon="building-2">Brand brief</SectionTitle>
          <div style={{ fontSize: 12.5, color: "var(--fg3)", marginBottom: 10 }}>Who you are, what you offer, and who you're for. Used as input when the AI generates campaign ideas.</div>
          <textarea defaultValue={brand.brandBrief} onBlur={(e) => { S.setBrand({ brandBrief: e.target.value }); onToast("Brand brief saved"); }}
            placeholder="e.g. Leap is an AI-powered social publishing tool for small brand teams. We help people post consistently across every channel without the daily scramble. Our audience is time-pressed social and marketing leads at small brands." style={taStyle} />
        </Card>
        <Card pad={20}>
          <SectionTitle icon="mic">Brand voice</SectionTitle>
          <div style={{ fontSize: 12.5, color: "var(--fg3)", marginBottom: 10 }}>The tone the AI writes posts in. Describe how your brand sounds — e.g. playful, formal, bold, warm.</div>
          <textarea defaultValue={brand.brandVoice} onBlur={(e) => { S.setBrand({ brandVoice: e.target.value }); onToast("Brand voice saved"); }}
            placeholder="e.g. Confident and plain-spoken, never hypey. Short sentences. Warm but not cutesy. We say 'you', never 'users'. No exclamation marks, no jargon." style={taStyle} />
        </Card>
      </div>
    );
  }

  // ---------------- Non-admin: personal view -----------------------------
  function MySettings({ onToast }) {
    const me = S.getCurrentUser();
    const m = S.getTeam().find((x) => x.name === me) || {};
    const settings = S.getNotifSettings();
    return (
      <div style={{ maxWidth: 700, margin: "0 auto", display: "flex", flexDirection: "column", gap: 16 }}>
        {S.getMyWizard()
          ? <ProfileEditor m={m} canEditRole={false} onToast={onToast} self />
          : <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", gap: 16, alignItems: "start" }} className="profile-2col">
              <ProfileEditor m={m} canEditRole={false} onToast={onToast} self />
              <div style={{ position: "sticky", top: 8 }}><BecomeWizardBox onToast={onToast} /></div>
            </div>}
        <Card pad={20}>
          <SectionTitle icon="bell">My notifications</SectionTitle>
          <div style={{ fontSize: 12, color: "var(--fg3)", marginBottom: 6 }}>Choose which notifications you receive. {settings.emailEnabled ? "Email delivery is on for the workspace." : "Email delivery is off for the workspace."}</div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {D.NOTIF_CATEGORIES.map((c) => (
              <label key={c.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--border)" }}>
                <Icon name={c.icon} size={17} color="var(--accent)" />
                <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1 }}>{c.label}</span>
                <Switch on={!!(m.notify && m.notify[c.id])} onChange={(v) => S.updateMemberNotify(m.id, c.id, v)} />
              </label>
            ))}
            <label style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0 2px" }}>
              <Icon name="mail" size={17} color={settings.emailEnabled ? "var(--success)" : "var(--fg4)"} />
              <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1 }}>Also email me{!settings.emailEnabled && <span style={{ fontSize: 11, color: "var(--fg4)", fontWeight: 500 }}> · disabled for the workspace</span>}</span>
              <Switch on={!!m.emailOn} onChange={(v) => S.updateMember(m.id, { emailOn: v })} />
            </label>
          </div>
        </Card>
        <WorkflowReadonly />
        <DangerZone onToast={onToast} meOnly />
      </div>
    );
  }

  function PreviewAs() {
    const cur = S.getCurrentUser();
    const locked = S.identityLocked && S.identityLocked();
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ fontSize: 11.5, color: "var(--fg3)", fontWeight: 600 }}>{locked ? "Signed in as" : "Preview as"}</span>
        {locked
          ? <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg1)", padding: "0 6px" }}>{cur}</span>
          : <Select value={cur} onChange={(v) => S.setCurrentUser(v)} style={{ width: 150 }} options={S.getTeam().map((m) => ({ value: m.name, label: `${m.name} · ${roleName(m.roleId)}` }))} />}
      </div>
    );
  }

  // ---------------- Danger zone: GDPR erasure (workspace + account) ------
  // Real, irreversible server-side deletions. Only meaningful when connected to a
  // live Leap workspace; the backend enforces owner-only + typed confirmation.
  function DangerZone({ onToast, meOnly }) {
    const gate = window.LeapGate;
    const A = window.LeapAPI;
    const live = !!(gate && gate.live());
    const [mode, setMode] = React.useState(null); // 'org' | 'me'
    const [preview, setPreview] = React.useState(null);
    const [typed, setTyped] = React.useState("");
    const [busy, setBusy] = React.useState(false);
    const ME_PHRASE = "DELETE MY ACCOUNT";

    const close = () => { if (!busy) { setMode(null); setPreview(null); setTyped(""); } };
    const openOrg = () => {
      setTyped(""); setPreview(null); setMode("org");
      A.account.erasurePreview(gate.orgId()).then(setPreview).catch(() => { onToast("Couldn't load workspace details", "error"); setMode(null); });
    };
    const openMe = () => { setTyped(""); setMode("me"); };
    const finish = (msg) => { onToast(msg); setTimeout(() => { try { A.logout(); } catch (e) {} try { localStorage.removeItem("leap_dev_token"); } catch (e) {} window.location.reload(); }, 1400); };

    async function doEraseOrg() {
      setBusy(true);
      try { await A.account.erase(gate.orgId(), typed); finish("Workspace deleted. Signing you out…"); }
      catch (e) { onToast(e.status === 403 ? "Only the workspace owner can delete it" : e.status === 400 ? "The name didn't match" : "Delete failed — please try again", "error"); setBusy(false); }
    }
    async function doEraseMe() {
      setBusy(true);
      try { await A.eraseMe(typed); finish("Your account was deleted. Signing you out…"); }
      catch (e) { onToast(e.status === 400 ? "Type the phrase exactly to confirm" : "Delete failed — please try again", "error"); setBusy(false); }
    }

    const orgPhrase = preview && preview.confirmationPhrase;
    const row = (title, desc, btn) => (
      <Card pad={20}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
          <div style={{ minWidth: 0 }}><div style={{ fontSize: 14, fontWeight: 700 }}>{title}</div><div style={{ fontSize: 12.5, color: "var(--fg3)", marginTop: 2, maxWidth: 470 }}>{desc}</div></div>
          {btn}
        </div>
      </Card>
    );

    return (
      <div style={{ maxWidth: 720, margin: "0 auto", display: "flex", flexDirection: "column", gap: 14 }}>
        <Card pad={18} style={{ border: "1px solid var(--danger)", background: "var(--danger-weak, rgba(220,50,50,0.06))" }}>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}><Icon name="alert-triangle" size={18} color="var(--danger)" /><div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--danger)" }}>Danger zone</div></div>
          <div style={{ fontSize: 12.5, color: "var(--fg3)", marginTop: 6 }}>Permanent, irreversible deletions.{!live ? " Available once you're connected to a live Leap workspace — the offline demo has no server data to erase." : " Please be certain."}</div>
        </Card>

        {live && !meOnly && row(
          "Delete this workspace",
          "Permanently erases this organization and everything in it — posts, campaigns, assets, connected accounts, team, analytics and billing record. Owner only.",
          <Button variant="danger" icon="trash-2" onClick={openOrg}>Delete workspace…</Button>,
        )}
        {live && row(
          "Delete my account",
          "Erases your personal data, sign-in and sessions (GDPR right to erasure). Any workspace where you're the only member is deleted with it.",
          <Button variant="danger" icon="user-x" onClick={openMe}>Delete account…</Button>,
        )}

        <Modal open={mode === "org"} title="Delete this workspace?" subtitle="This cannot be undone." width={520} onClose={close}
          footer={<React.Fragment>
            <Button variant="secondary" onClick={close} disabled={busy}>Cancel</Button>
            <Button variant="danger" icon="trash-2" disabled={busy || !preview || !preview.isOwner || typed !== orgPhrase} onClick={doEraseOrg}>{busy ? "Deleting…" : "Permanently delete"}</Button>
          </React.Fragment>}>
          {!preview ? <div style={{ fontSize: 13, color: "var(--fg3)" }}>Loading…</div> : (
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {!preview.isOwner && <div style={{ fontSize: 12.5, color: "var(--danger)", background: "var(--danger-weak, rgba(220,50,50,0.08))", border: "1px solid var(--danger)", borderRadius: 10, padding: "9px 11px" }}>Only the workspace <b>owner</b> can delete it. Ask an owner to do this.</div>}
              <div style={{ fontSize: 13, color: "var(--fg2)" }}>This permanently erases <b>{preview.org.name}</b> and everything in it:</div>
              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: "var(--fg3)", lineHeight: 1.7 }}>{preview.categories.map((c, i) => <li key={i}>{c}</li>)}</ul>
              <div><Label>Type <b>{preview.confirmationPhrase}</b> to confirm</Label><input value={typed} onChange={(e) => setTyped(e.target.value)} placeholder={preview.confirmationPhrase} disabled={!preview.isOwner} style={fieldStyle} /></div>
            </div>
          )}
        </Modal>

        <Modal open={mode === "me"} title="Delete your account?" subtitle="This cannot be undone." width={480} onClose={close}
          footer={<React.Fragment>
            <Button variant="secondary" onClick={close} disabled={busy}>Cancel</Button>
            <Button variant="danger" icon="user-x" disabled={busy || typed !== ME_PHRASE} onClick={doEraseMe}>{busy ? "Deleting…" : "Delete my account"}</Button>
          </React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div style={{ fontSize: 13, color: "var(--fg2)" }}>This erases your personal data, sign-in and sessions. Any workspace where you're the sole member is deleted with it.</div>
            <div><Label>Type <b>{ME_PHRASE}</b> to confirm</Label><input value={typed} onChange={(e) => setTyped(e.target.value)} placeholder={ME_PHRASE} style={fieldStyle} /></div>
          </div>
        </Modal>
      </div>
    );
  }

  function SettingsView({ onToast }) {
    const [tab, setTab] = React.useState("profile");
    const admin = S.isAdmin();
    if (!admin) return <MySettings onToast={onToast} />;
    const team = S.getScopedTeam(), roles = S.getRoles(), settings = S.getNotifSettings();
    const me = S.currentMember() || {};
    return (
      <div style={{ maxWidth: "var(--page-w)", margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
          <Segmented value={tab} onChange={setTab} options={[
            { value: "profile", label: "Profile", icon: "user" },
            { value: "brand", label: "Brand", icon: "sparkles" },
            { value: "people", label: "People", icon: "users" },
            { value: "roles", label: "Roles", icon: "shield" },
            { value: "workflow", label: "Workflow", icon: "git-branch" },
            { value: "postsetup", label: "Post setup", icon: "sliders-horizontal" },
            { value: "notif", label: "Notifications", icon: "bell" },
            { value: "house", label: "House rules", icon: "scroll-text" },
            { value: "channels", label: "Channels", icon: "radio" },
            { value: "integrations", label: "Integrations", icon: "plug" },
            { value: "danger", label: "Danger", icon: "alert-triangle" },
          ]} />
          <div style={{ flex: 1 }} />
          <button onClick={() => S.restartOnboarding()} title="Run the setup journey again" style={{ display: "inline-flex", alignItems: "center", gap: 6, border: "1px solid var(--border-strong)", background: "var(--surface)", borderRadius: 999, padding: "6px 12px", cursor: "pointer", fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "var(--fg2)" }}><Icon name="sparkles" size={14} color="var(--accent)" />Re-run setup</button>
          <PreviewAs />
        </div>
        {tab === "profile" && (S.getMyWizard()
          ? <div style={{ maxWidth: 700 }}><ProfileEditor m={me} canEditRole={false} onToast={onToast} self /></div>
          : <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", gap: 16, alignItems: "start" }} className="profile-2col">
              <ProfileEditor m={me} canEditRole={false} onToast={onToast} self />
              <div style={{ position: "sticky", top: 8 }}><BecomeWizardBox onToast={onToast} /></div>
            </div>)}
        {tab === "brand" && <BrandSettings onToast={onToast} />}
        {tab === "people" && <People team={team} roles={roles} onToast={onToast} />}
        {tab === "roles" && <RolesRights roles={roles} onToast={onToast} />}
        {tab === "workflow" && <WorkflowEditor onToast={onToast} />}
        {tab === "postsetup" && <PostSetup onToast={onToast} />}
        {tab === "notif" && <NotifRouting team={team} settings={settings} onToast={onToast} />}
        {tab === "house" && <HouseRules onToast={onToast} />}
        {tab === "channels" && <Channels onToast={onToast} />}
        {tab === "integrations" && <Integrations onToast={onToast} />}
        {tab === "danger" && <DangerZone onToast={onToast} />}
      </div>
    );
  }
  window.SettingsView = SettingsView;
})();
