// Settings page — cloud, Slack, team members + general workspace config.
const { useState: useStateS } = React;

function SettingsPage({ role }) {
  const isOperator = role === "operator";
  const [section, setSection] = useStateS(isOperator ? "notifications" : "workspace");

  const sections = isOperator
    ? [
        { id: "profile",       label: "My profile",      icon: "Users" },
        { id: "notifications", label: "Notifications",   icon: "Bell"  },
        { id: "tokens",        label: "Personal tokens", icon: "Key"   },
      ]
    : [
        { id: "workspace", label: "Workspace",     icon: "Gear"     },
        { id: "members",   label: "Team & roles",  icon: "Users"    },
        { id: "cloud",     label: "Cloud (BYOC)",  icon: "Cloud"    },
        { id: "slack",     label: "Slack",         icon: "Hash"     },
        { id: "github",    label: "GitHub",        icon: "Code"     },
        { id: "sso",       label: "SSO & SCIM",    icon: "Shield"   },
        { id: "audit",     label: "Audit log",     icon: "Doc"      },
        { id: "tokens",    label: "API tokens",    icon: "Key"      },
      ];

  return (
    <div className="fade-in">
      <div style={{ marginBottom: 22 }}>
        <div className="eyebrow">{isOperator ? `Personal · ${DATA.ME_OPERATOR.name}` : "Workspace · Organization"}</div>
        <h1 className="page-title" style={{ marginTop: 8 }}>{isOperator ? "Your settings." : "Settings."}</h1>
        <p className="page-sub">{isOperator ? "Where you get pinged, your personal API tokens, and your profile." : "Members and roles, your own cloud, Slack routing, SSO, and the integrations Stoda uses to do its job."}</p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 24, alignItems: "flex-start" }}>
        {/* Sub-nav */}
        <nav style={{ position: "sticky", top: 24, display: "flex", flexDirection: "column", gap: 2 }}>
          {sections.map(s => {
            const Ic = Icons[s.icon] || Icons.Gear;
            const active = section === s.id;
            return (
              <button key={s.id} onClick={() => setSection(s.id)}
                style={{
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "9px 12px", border: "none", borderRadius: 8,
                  background: active ? "var(--cream-3)" : "transparent",
                  color: active ? "var(--ink)" : "var(--muted)",
                  fontSize: 13, fontWeight: active ? 500 : 400,
                  cursor: "pointer", textAlign: "left",
                }}>
                <span style={{ width: 16, height: 16, display: "inline-flex", alignItems: "center", justifyContent: "center", color: active ? "var(--ink)" : "var(--ink-3)" }}>
                  <Ic s={14}/>
                </span>
                {s.label}
              </button>
            );
          })}
        </nav>

        <div>
          {section === "workspace"     && <WorkspacePanel/>}
          {section === "members"       && <MembersPanel/>}
          {section === "cloud"         && <CloudPanel/>}
          {section === "slack"         && <SlackPanel/>}
          {section === "github"        && <GitHubPanel/>}
          {section === "sso"           && <SSOPanel/>}
          {section === "audit"         && <AuditPanel/>}
          {section === "tokens"        && (isOperator ? <PersonalTokensPanel/> : <TokensPanel/>)}
          {section === "profile"       && <ProfilePanel/>}
          {section === "notifications" && <PersonalNotificationsPanel/>}
        </div>
      </div>
    </div>
  );
}

// ---------- Shared ----------
function SettingRow({ label, hint, children, danger }) {
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "260px 1fr",
      gap: 24, padding: "18px 20px",
      borderTop: "1px solid var(--tan-2)",
      alignItems: "flex-start",
    }}>
      <div>
        <div style={{ fontSize: 13, fontWeight: 500, color: danger ? "var(--red)" : "var(--ink)" }}>{label}</div>
        {hint && <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4, lineHeight: 1.45 }}>{hint}</div>}
      </div>
      <div>{children}</div>
    </div>
  );
}

function PanelHeader({ title, subtitle, status }) {
  return (
    <div style={{ padding: "20px 20px 16px", display: "flex", alignItems: "flex-start", gap: 12 }}>
      <div style={{ flex: 1 }}>
        <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 400, letterSpacing: "-0.02em" }}>{title}</h3>
        {subtitle && <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 4, maxWidth: "62ch" }}>{subtitle}</div>}
      </div>
      {status}
    </div>
  );
}

function StatusChip({ kind, children }) {
  const styles = {
    ok:    { color: "var(--green-text)", bg: "var(--paper)", border: "var(--green-border)", dot: "var(--green)" },
    warn:  { color: "var(--amber-text)", bg: "var(--paper)", border: "var(--amber-border)", dot: "var(--amber)" },
    risk:  { color: "var(--red)",        bg: "var(--paper)", border: "color-mix(in srgb, var(--red) 30%, var(--tan-2))", dot: "var(--red)" },
    off:   { color: "var(--muted)",      bg: "var(--paper)", border: "var(--tan-2)", dot: "var(--ink-3)" },
  }[kind || "off"];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 10px", fontSize: 11.5, fontWeight: 500, color: styles.color, background: styles.bg, border: `1px solid ${styles.border}`, borderRadius: 999 }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: styles.dot }}/>
      {children}
    </span>
  );
}

function TextField({ value, onChange, mono, placeholder, width = 320 }) {
  return (
    <input value={value} onChange={(e) => onChange && onChange(e.target.value)} placeholder={placeholder}
      style={{
        width, padding: "8px 10px",
        background: "var(--paper)", border: "1px solid var(--tan-2)",
        borderRadius: 6, fontSize: 12.5,
        fontFamily: mono ? "var(--mono)" : "inherit",
        color: "var(--ink)",
      }}/>
  );
}

function Toggle({ on, onChange, label }) {
  return (
    <button onClick={() => onChange && onChange(!on)} style={{
      display: "inline-flex", alignItems: "center", gap: 8,
      padding: 0, background: "transparent", border: "none", cursor: "pointer",
    }}>
      <span style={{
        width: 32, height: 18, borderRadius: 999,
        background: on ? "var(--green)" : "var(--tan-3)",
        position: "relative", transition: "background 0.15s",
      }}>
        <span style={{
          position: "absolute", top: 2, left: on ? 16 : 2,
          width: 14, height: 14, borderRadius: "50%",
          background: "var(--paper)", transition: "left 0.15s",
        }}/>
      </span>
      {label && <span style={{ fontSize: 12.5, color: "var(--ink)" }}>{label}</span>}
    </button>
  );
}

// ---------- Workspace ----------
function WorkspacePanel() {
  const [name, setName] = useStateS("Meridia");
  const [domain, setDomain] = useStateS("meridia.co");
  const [region, setRegion] = useStateS("us-east-1");
  const [retention, setRetention] = useStateS("180");

  return (
    <div className="card flush">
      <PanelHeader title="Workspace" subtitle="Organization-level settings, applied across every app and operator."/>
      <SettingRow label="Workspace name" hint="Shown in the sidebar, evidence pack, and Slack notifications.">
        <TextField value={name} onChange={setName}/>
      </SettingRow>
      <SettingRow label="Primary domain" hint="Used for SSO email matching and outbound allowlists.">
        <TextField value={domain} onChange={setDomain} mono/>
      </SettingRow>
      <SettingRow label="Default region" hint="Where Stoda runs deployments unless an app overrides it.">
        <select value={region} onChange={(e) => setRegion(e.target.value)} style={{ padding: "8px 10px", background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 6, fontSize: 12.5, color: "var(--ink)" }}>
          <option value="us-east-1">us-east-1 · N. Virginia</option>
          <option value="us-west-2">us-west-2 · Oregon</option>
          <option value="eu-west-1">eu-west-1 · Ireland</option>
          <option value="ap-southeast-2">ap-southeast-2 · Sydney</option>
        </select>
      </SettingRow>
      <SettingRow label="Audit log retention" hint="Days to keep raw events. Evidence packs are retained separately.">
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <TextField value={retention} onChange={setRetention} width={80}/>
          <span style={{ fontSize: 12.5, color: "var(--muted)" }}>days</span>
        </div>
      </SettingRow>
      <SettingRow label="Delete workspace" hint="Removes all apps, rules, and history. This cannot be undone." danger>
        <button style={{ padding: "7px 14px", background: "var(--paper)", border: "1px solid color-mix(in srgb, var(--red) 30%, var(--tan-2))", color: "var(--red)", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer" }}>Delete workspace</button>
      </SettingRow>
    </div>
  );
}

// ---------- Members ----------
const MEMBERS = [
  { id: "pr", name: "Priya Rangarajan", email: "priya@meridia.co",   role: "Admin",     team: "Engineering",      initials: "PR", color: "#D8C8E8", status: "active" },
  { id: "ml", name: "Maya Lindqvist",   email: "maya@meridia.co",    role: "Operator",  team: "Revenue Ops",      initials: "ML", color: "#FFB98A", status: "active" },
  { id: "rp", name: "Rohan Patel",      email: "rohan@meridia.co",   role: "Operator",  team: "Finance",          initials: "RP", color: "#B4D0B0", status: "active" },
  { id: "sj", name: "Sam Jefferson",    email: "sam@meridia.co",     role: "Operator",  team: "Customer Success", initials: "SJ", color: "#D9C7E8", status: "active" },
  { id: "tt", name: "Thalia Torres",    email: "thalia@meridia.co",  role: "Reviewer",  team: "Marketing",        initials: "TT", color: "#F4C9B0", status: "active" },
  { id: "ay", name: "Ayaan Younis",     email: "ayaan@meridia.co",   role: "Operator",  team: "People Ops",       initials: "AY", color: "#C7D9E8", status: "active" },
  { id: "dk", name: "Diego Kovač",      email: "diego@meridia.co",   role: "Reviewer",  team: "Legal",            initials: "DK", color: "#D0B0B4", status: "invited" },
];

function MembersPanel() {
  const [members, setMembers] = useStateS(MEMBERS);
  const [showInvite, setShowInvite] = useStateS(false);
  const [filter, setFilter] = useStateS("all");

  const filtered = filter === "all" ? members : members.filter(m => m.role.toLowerCase() === filter);

  return (
    <>
      <div className="card flush">
        <PanelHeader
          title="Team & roles"
          subtitle={`${members.filter(m => m.status === "active").length} active · ${members.filter(m => m.status === "invited").length} pending invite. Roles determine what a member can deploy, approve, or override.`}
          status={
            <button onClick={() => setShowInvite(true)} style={{ padding: "7px 14px", background: "var(--ink-2)", color: "#fff", border: "none", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6 }}>
              <Icons.Plus s={11}/> Invite member
            </button>
          }/>

        {/* Filter pills */}
        <div style={{ display: "flex", gap: 6, padding: "0 20px 14px" }}>
          {[
            { v: "all",      label: `All (${members.length})` },
            { v: "admin",    label: `Admins (${members.filter(m => m.role === "Admin").length})` },
            { v: "operator", label: `Operators (${members.filter(m => m.role === "Operator").length})` },
            { v: "reviewer", label: `Reviewers (${members.filter(m => m.role === "Reviewer").length})` },
          ].map(f => (
            <button key={f.v} onClick={() => setFilter(f.v)} style={{
              padding: "5px 11px", fontSize: 12, fontWeight: 500,
              border: filter === f.v ? "1px solid var(--ink-3)" : "1px solid var(--tan-2)",
              background: filter === f.v ? "var(--cream-3)" : "var(--paper)",
              color: "var(--ink)", borderRadius: 999, cursor: "pointer",
            }}>{f.label}</button>
          ))}
        </div>

        <table className="t" style={{ borderTop: "1px solid var(--tan-2)" }}>
          <thead><tr><th>Member</th><th>Team</th><th>Role</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {filtered.map(m => (
              <tr key={m.id}>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <span className="avatar" style={{ width: 30, height: 30, fontSize: 11, background: m.color, borderRadius: "50%", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--ink)", fontWeight: 500 }}>{m.initials}</span>
                    <div>
                      <div style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500 }}>{m.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--muted)" }}>{m.email}</div>
                    </div>
                  </div>
                </td>
                <td><span style={{ fontSize: 12, color: "var(--muted)" }}>{m.team}</span></td>
                <td>
                  <select value={m.role} onChange={(e) => setMembers(prev => prev.map(x => x.id === m.id ? { ...x, role: e.target.value } : x))}
                    style={{ padding: "5px 8px", background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 6, fontSize: 12, color: "var(--ink)" }}>
                    <option>Admin</option>
                    <option>Operator</option>
                    <option>Reviewer</option>
                  </select>
                </td>
                <td>
                  {m.status === "active"
                    ? <StatusChip kind="ok">Active</StatusChip>
                    : <StatusChip kind="warn">Invite pending</StatusChip>}
                </td>
                <td style={{ textAlign: "right" }}>
                  <button onClick={() => setMembers(prev => prev.filter(x => x.id !== m.id))}
                    style={{ padding: "4px 8px", background: "transparent", border: "1px solid var(--tan-2)", color: "var(--muted)", borderRadius: 6, fontSize: 11.5, cursor: "pointer" }}>
                    Remove
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Roles legend */}
        <div style={{ padding: "16px 20px", borderTop: "1px solid var(--tan-2)", background: "var(--cream-2)", display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
          <RoleDef name="Admin"    line="Manages workspace, billing, members, and integrations."/>
          <RoleDef name="Operator" line="Owns apps, ships deploys, and writes rules within their team."/>
          <RoleDef name="Reviewer" line="Read-only on apps + governance. Can comment, approve exceptions."/>
        </div>
      </div>

      {showInvite && <InviteModal onClose={() => setShowInvite(false)} onInvite={(m) => { setMembers(prev => [...prev, m]); setShowInvite(false); }}/>}
    </>
  );
}

function RoleDef({ name, line }) {
  return (
    <div>
      <div style={{ fontSize: 12, fontWeight: 500, color: "var(--ink)" }}>{name}</div>
      <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 3, lineHeight: 1.4 }}>{line}</div>
    </div>
  );
}

function InviteModal({ onClose, onInvite }) {
  const [email, setEmail] = useStateS("");
  const [role, setRole] = useStateS("Operator");
  const [team, setTeam] = useStateS("");
  const [bulk, setBulk] = useStateS(false);

  const submit = () => {
    if (!email) return;
    const initials = email.slice(0, 2).toUpperCase();
    const colors = ["#FFB98A", "#B4D0B0", "#D9C7E8", "#F4C9B0", "#C7D9E8", "#D0B0B4", "#E8D9C7"];
    onInvite({
      id: Math.random().toString(36).slice(2, 7),
      name: email.split("@")[0].replace(/\./g, " ").replace(/\b\w/g, c => c.toUpperCase()),
      email, role, team: team || "—",
      initials, color: colors[Math.floor(Math.random() * colors.length)],
      status: "invited",
    });
  };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(20, 18, 14, 0.4)", zIndex: 80, display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 480, background: "var(--paper)", borderRadius: 12, border: "1px solid var(--tan-2)", boxShadow: "0 20px 60px rgba(0,0,0,0.18)" }}>
        <div style={{ padding: "20px 22px", borderBottom: "1px solid var(--tan-2)" }}>
          <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 400, letterSpacing: "-0.02em" }}>Invite a member</h3>
          <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 4 }}>They'll get an email with a link to join your workspace.</div>
        </div>
        <div style={{ padding: 22, display: "grid", gap: 14 }}>
          <div>
            <label style={{ display: "block", fontSize: 12, color: "var(--ink)", fontWeight: 500, marginBottom: 6 }}>Email</label>
            {!bulk
              ? <TextField value={email} onChange={setEmail} placeholder="name@meridia.co" width="100%"/>
              : <textarea value={email} onChange={(e) => setEmail(e.target.value)} placeholder="One email per line" rows={4}
                  style={{ width: "100%", padding: "8px 10px", background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 6, fontSize: 12.5, fontFamily: "var(--mono)", color: "var(--ink)", resize: "vertical" }}/>}
            <button onClick={() => setBulk(!bulk)} style={{ marginTop: 6, padding: 0, background: "transparent", border: "none", color: "var(--accent)", fontSize: 11.5, cursor: "pointer" }}>
              {bulk ? "← Single invite" : "Bulk invite →"}
            </button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div>
              <label style={{ display: "block", fontSize: 12, color: "var(--ink)", fontWeight: 500, marginBottom: 6 }}>Role</label>
              <select value={role} onChange={(e) => setRole(e.target.value)} style={{ width: "100%", padding: "8px 10px", background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 6, fontSize: 12.5, color: "var(--ink)" }}>
                <option>Admin</option>
                <option>Operator</option>
                <option>Reviewer</option>
              </select>
            </div>
            <div>
              <label style={{ display: "block", fontSize: 12, color: "var(--ink)", fontWeight: 500, marginBottom: 6 }}>Team</label>
              <TextField value={team} onChange={setTeam} placeholder="e.g. Revenue Ops" width="100%"/>
            </div>
          </div>
          <div style={{ padding: "10px 12px", background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 8, fontSize: 11.5, color: "var(--muted)", lineHeight: 1.5 }}>
            <b style={{ color: "var(--ink)" }}>{role === "Admin" ? "Admins" : role === "Operator" ? "Operators" : "Reviewers"}</b>{" "}
            {role === "Admin"    && "can do everything in this workspace, including billing and member management."}
            {role === "Operator" && "can ship apps, deploy, and create rules within their team."}
            {role === "Reviewer" && "can read everything and approve exceptions, but cannot deploy."}
          </div>
        </div>
        <div style={{ padding: "14px 22px", borderTop: "1px solid var(--tan-2)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button onClick={onClose} style={{ padding: "7px 14px", background: "var(--paper)", border: "1px solid var(--tan-2)", color: "var(--ink)", borderRadius: 6, fontSize: 12.5, cursor: "pointer" }}>Cancel</button>
          <button onClick={submit} style={{ padding: "7px 14px", background: "var(--ink-2)", color: "#fff", border: "none", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer" }}>Send invite</button>
        </div>
      </div>
    </div>
  );
}

// ---------- Cloud (BYOC) ----------
function CloudPanel() {
  const [provider, setProvider] = useStateS("aws");
  const [connected, setConnected] = useStateS(true);
  const [showWizard, setShowWizard] = useStateS(false);

  return (
    <>
      <div className="card flush">
        <PanelHeader
          title="Cloud (Bring your own)"
          subtitle="Stoda runs your apps inside your own cloud account so data, secrets, and compute never leave it. We connect via a least-privilege role."
          status={connected ? <StatusChip kind="ok">Connected</StatusChip> : <StatusChip kind="off">Not connected</StatusChip>}/>

        {/* Provider selector */}
        <div style={{ padding: "0 20px 18px", display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
          {[
            { v: "aws",   name: "Amazon Web Services", short: "AWS",   color: "#FF9900" },
            { v: "gcp",   name: "Google Cloud",         short: "GCP",   color: "#4285F4" },
            { v: "azure", name: "Microsoft Azure",      short: "Azure", color: "#0078D4" },
          ].map(p => (
            <button key={p.v} onClick={() => setProvider(p.v)} style={{
              padding: 14, textAlign: "left",
              background: provider === p.v ? "var(--cream-3)" : "var(--paper)",
              border: provider === p.v ? "1px solid var(--ink-3)" : "1px solid var(--tan-2)",
              borderRadius: 10, cursor: "pointer",
              display: "flex", alignItems: "center", gap: 12,
            }}>
              <span style={{ width: 32, height: 32, borderRadius: 8, background: `color-mix(in srgb, ${p.color} 14%, var(--paper))`, color: p.color, display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 11, fontFamily: "var(--mono)" }}>{p.short}</span>
              <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--ink)" }}>{p.name}</div>
            </button>
          ))}
        </div>

        {provider === "aws" && (
          <>
            <SettingRow label="Account ID" hint="The AWS account Stoda has been authorized to deploy into.">
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <code style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink)", padding: "6px 10px", background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 6 }}>847203195642</code>
                <StatusChip kind="ok">Verified</StatusChip>
              </div>
            </SettingRow>
            <SettingRow label="IAM role" hint="Least-privilege role assumed by Stoda's runtime. Audit any time in your IAM console.">
              <code style={{ display: "block", fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink)", padding: "8px 10px", background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 6, maxWidth: 480, overflowX: "auto" }}>
                arn:aws:iam::847203195642:role/StodaRuntime
              </code>
            </SettingRow>
            <SettingRow label="VPC" hint="Where deployments run. New VPCs can be created from the wizard.">
              <select style={{ padding: "8px 10px", background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 6, fontSize: 12.5, color: "var(--ink)", minWidth: 320 }}>
                <option>vpc-0a4f8e2b · stoda-prod (us-east-1)</option>
                <option>vpc-0c1d3a9f · stoda-staging (us-east-1)</option>
              </select>
            </SettingRow>
            <SettingRow label="Connection health" hint="Last verified 4 minutes ago. Stoda re-verifies hourly.">
              <div style={{ display: "flex", gap: 8 }}>
                <StatusChip kind="ok">All checks passing</StatusChip>
                <button style={{ padding: "5px 10px", background: "var(--paper)", border: "1px solid var(--tan-2)", color: "var(--ink)", borderRadius: 6, fontSize: 11.5, cursor: "pointer" }}>Re-verify now</button>
              </div>
            </SettingRow>
            <SettingRow label="Disconnect" hint="Stops all Stoda-managed deploys. Apps continue running until you remove them." danger>
              <button onClick={() => setConnected(false)} style={{ padding: "7px 14px", background: "var(--paper)", border: "1px solid color-mix(in srgb, var(--red) 30%, var(--tan-2))", color: "var(--red)", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer" }}>Disconnect AWS</button>
            </SettingRow>
          </>
        )}

        {provider !== "aws" && (
          <div style={{ padding: "32px 20px 28px", borderTop: "1px solid var(--tan-2)", textAlign: "center" }}>
            <div style={{ fontSize: 13.5, color: "var(--ink)", fontWeight: 500 }}>{provider === "gcp" ? "Google Cloud" : "Azure"} not connected</div>
            <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 6, maxWidth: 380, margin: "6px auto 14px" }}>
              Connect your {provider === "gcp" ? "GCP project" : "Azure subscription"} so Stoda can deploy into it. Takes about 3 minutes.
            </div>
            <button onClick={() => setShowWizard(true)} style={{ padding: "8px 16px", background: "var(--ink-2)", color: "#fff", border: "none", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer" }}>
              Connect {provider === "gcp" ? "GCP" : "Azure"}
            </button>
          </div>
        )}
      </div>

      {showWizard && <CloudWizard provider={provider} onClose={() => setShowWizard(false)}/>}
    </>
  );
}

function CloudWizard({ provider, onClose }) {
  const [step, setStep] = useStateS(1);
  const providerName = provider === "gcp" ? "Google Cloud" : "Azure";

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(20, 18, 14, 0.4)", zIndex: 80, display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 560, background: "var(--paper)", borderRadius: 12, border: "1px solid var(--tan-2)", boxShadow: "0 20px 60px rgba(0,0,0,0.18)" }}>
        <div style={{ padding: "20px 22px", borderBottom: "1px solid var(--tan-2)" }}>
          <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 400, letterSpacing: "-0.02em" }}>Connect {providerName}</h3>
          <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 4 }}>Step {step} of 3</div>
          <div style={{ display: "flex", gap: 4, marginTop: 12 }}>
            {[1,2,3].map(i => <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i <= step ? "var(--ink-2)" : "var(--tan-2)" }}/>)}
          </div>
        </div>
        <div style={{ padding: 22, minHeight: 240 }}>
          {step === 1 && (
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--ink)" }}>Open your {providerName} console</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 6 }}>You'll create a service account / role with the policy below. Stoda assumes it; no long-lived credentials.</div>
              <div style={{ marginTop: 14, padding: 12, background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 8, fontFamily: "var(--mono)", fontSize: 11.5, color: "var(--ink)", whiteSpace: "pre-wrap" }}>
{provider === "gcp"
? `gcloud iam service-accounts create stoda-runtime \\
  --display-name="Stoda Runtime"
gcloud projects add-iam-policy-binding YOUR_PROJECT \\
  --member="serviceAccount:stoda-runtime@..." \\
  --role="roles/run.admin"`
: `az ad sp create-for-rbac --name stoda-runtime \\
  --role contributor \\
  --scopes /subscriptions/YOUR_SUB`}
              </div>
            </div>
          )}
          {step === 2 && (
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--ink)" }}>Paste the credentials</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 6, marginBottom: 14 }}>{provider === "gcp" ? "Service-account JSON key" : "Tenant ID, Client ID, Client Secret"}</div>
              <textarea placeholder={provider === "gcp" ? '{"type": "service_account", ...}' : "tenant=...\nclient_id=...\nclient_secret=..."} rows={6}
                style={{ width: "100%", padding: 10, background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 6, fontFamily: "var(--mono)", fontSize: 11.5, color: "var(--ink)", resize: "vertical" }}/>
            </div>
          )}
          {step === 3 && (
            <div style={{ textAlign: "center", padding: "20px 0" }}>
              <div style={{ width: 48, height: 48, margin: "0 auto", borderRadius: "50%", background: "var(--paper)", border: "2px solid var(--green)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--green)" }}>✓</div>
              <div style={{ fontSize: 15, fontWeight: 500, color: "var(--ink)", marginTop: 14 }}>Connection verified</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 6, maxWidth: 360, margin: "6px auto 0" }}>Stoda can now deploy into your {providerName} account. You can pick a default region in Workspace settings.</div>
            </div>
          )}
        </div>
        <div style={{ padding: "14px 22px", borderTop: "1px solid var(--tan-2)", display: "flex", justifyContent: "space-between" }}>
          <button onClick={() => step === 1 ? onClose() : setStep(step - 1)} style={{ padding: "7px 14px", background: "var(--paper)", border: "1px solid var(--tan-2)", color: "var(--ink)", borderRadius: 6, fontSize: 12.5, cursor: "pointer" }}>{step === 1 ? "Cancel" : "Back"}</button>
          <button onClick={() => step === 3 ? onClose() : setStep(step + 1)} style={{ padding: "7px 14px", background: "var(--ink-2)", color: "#fff", border: "none", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer" }}>{step === 3 ? "Done" : step === 2 ? "Verify" : "Next"}</button>
        </div>
      </div>
    </div>
  );
}

// ---------- Slack ----------
function SlackPanel() {
  const [connected, setConnected] = useStateS(true);
  const [routes, setRoutes] = useStateS([
    { id: 1, event: "Held deploy",         channel: "#stoda-deploys", who: "Owner + Admins",       on: true  },
    { id: 2, event: "Drift detected",      channel: "#stoda-deploys", who: "Owner",                on: true  },
    { id: 3, event: "Budget breach",       channel: "#stoda-cost",    who: "Owner + Finance team", on: true  },
    { id: 4, event: "New outbound domain", channel: "#stoda-deploys", who: "Admins",               on: true  },
    { id: 5, event: "Test failure",        channel: "#stoda-tests",   who: "Owner",                on: true  },
    { id: 6, event: "Daily fleet digest",  channel: "#stoda-fleet",   who: "All operators",        on: false },
    { id: 7, event: "Weekly evidence pack",channel: "#compliance",    who: "Reviewers",            on: true  },
  ]);
  const channels = ["#stoda-deploys", "#stoda-cost", "#stoda-tests", "#stoda-fleet", "#compliance", "#engineering", "#alerts"];

  return (
    <div className="card flush">
      <PanelHeader
        title="Slack"
        subtitle="Where Stoda sends notifications. Each event can route to a different channel and audience."
        status={connected ? <StatusChip kind="ok">Connected to meridia.slack.com</StatusChip> : <StatusChip kind="off">Not connected</StatusChip>}/>

      {!connected && (
        <div style={{ padding: "32px 20px", textAlign: "center", borderTop: "1px solid var(--tan-2)" }}>
          <button onClick={() => setConnected(true)} style={{ padding: "8px 18px", background: "#4A154B", color: "#fff", border: "none", borderRadius: 6, fontSize: 13, fontWeight: 500, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8 }}>
            <span style={{ width: 14, height: 14, borderRadius: 3, background: "#fff", color: "#4A154B", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 10 }}>#</span>
            Add to Slack
          </button>
        </div>
      )}

      {connected && (
        <>
          <SettingRow label="Workspace" hint="The Slack workspace this integration is connected to.">
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ width: 28, height: 28, borderRadius: 6, background: "#4A154B", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12 }}>M</span>
              <div>
                <div style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500 }}>meridia.slack.com</div>
                <div style={{ fontSize: 11.5, color: "var(--muted)" }}>Connected by Priya Rangarajan · Apr 12</div>
              </div>
            </div>
          </SettingRow>

          <SettingRow label="Default channel" hint="Used when an event has no specific channel set.">
            <select defaultValue="#stoda-deploys" style={{ padding: "8px 10px", background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 6, fontSize: 12.5, color: "var(--ink)", minWidth: 220 }}>
              {channels.map(c => <option key={c}>{c}</option>)}
            </select>
          </SettingRow>

          {/* Event routing table */}
          <div style={{ borderTop: "1px solid var(--tan-2)", padding: "18px 20px" }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>Event routing</div>
            <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4, marginBottom: 14 }}>One row per event Stoda can notify on. Toggle off to silence; pick a channel and audience per event.</div>
            <table className="t" style={{ background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 8, overflow: "hidden" }}>
              <thead><tr><th>Event</th><th>Channel</th><th>Notify</th><th style={{ width: 60 }}>On</th></tr></thead>
              <tbody>
                {routes.map(r => (
                  <tr key={r.id} style={{ opacity: r.on ? 1 : 0.55 }}>
                    <td style={{ fontSize: 12.5, color: "var(--ink)", fontWeight: 500 }}>{r.event}</td>
                    <td>
                      <select value={r.channel} onChange={(e) => setRoutes(prev => prev.map(x => x.id === r.id ? { ...x, channel: e.target.value } : x))}
                        style={{ padding: "5px 8px", background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 6, fontSize: 12, fontFamily: "var(--mono)", color: "var(--ink)" }}>
                        {channels.map(c => <option key={c}>{c}</option>)}
                      </select>
                    </td>
                    <td><span style={{ fontSize: 12, color: "var(--muted)" }}>{r.who}</span></td>
                    <td><Toggle on={r.on} onChange={(v) => setRoutes(prev => prev.map(x => x.id === r.id ? { ...x, on: v } : x))}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <SettingRow label="Quiet hours" hint="Suppress non-urgent notifications outside business hours.">
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <Toggle on={true} onChange={() => {}}/>
              <span style={{ fontSize: 12, color: "var(--muted)" }}>9:00 PM – 7:00 AM, recipient's local time</span>
            </div>
          </SettingRow>

          <SettingRow label="Test message" hint="Send a sample alert to confirm routing works.">
            <button style={{ padding: "7px 14px", background: "var(--paper)", border: "1px solid var(--tan-2)", color: "var(--ink)", borderRadius: 6, fontSize: 12.5, cursor: "pointer" }}>Send test to #stoda-deploys</button>
          </SettingRow>
        </>
      )}
    </div>
  );
}

// ---------- GitHub (lightweight stub) ----------
function GitHubPanel() {
  return (
    <div className="card flush">
      <PanelHeader title="GitHub" subtitle="Source for app code. Stoda runs scans on every PR and links each deploy to a commit." status={<StatusChip kind="ok">Connected · meridia-co</StatusChip>}/>
      <SettingRow label="Organization" hint="Repos under this GitHub org are visible to Stoda.">
        <code style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink)", padding: "6px 10px", background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 6 }}>github.com/meridia-co</code>
      </SettingRow>
      <SettingRow label="Repos in scope" hint="24 of 41 repos are managed by Stoda.">
        <button style={{ padding: "7px 14px", background: "var(--paper)", border: "1px solid var(--tan-2)", color: "var(--ink)", borderRadius: 6, fontSize: 12.5, cursor: "pointer" }}>Manage repos</button>
      </SettingRow>
      <SettingRow label="PR checks" hint="Stoda posts a check on every PR with rule pass/fail.">
        <Toggle on={true} onChange={() => {}} label="Enabled"/>
      </SettingRow>
    </div>
  );
}

// ---------- SSO / Audit / Tokens stubs ----------
function SSOPanel() {
  return (
    <div className="card flush">
      <PanelHeader title="SSO & SCIM" subtitle="Single sign-on via SAML / OIDC, plus user provisioning." status={<StatusChip kind="ok">Okta · SAML</StatusChip>}/>
      <SettingRow label="Provider" hint="Configured at the IdP. Stoda accepts assertions, never holds a password."><code style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink)", padding: "6px 10px", background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 6 }}>meridia.okta.com</code></SettingRow>
      <SettingRow label="SCIM provisioning" hint="Auto-create / deactivate Stoda accounts when users join or leave Okta."><Toggle on={true} onChange={() => {}} label="Enabled"/></SettingRow>
      <SettingRow label="Enforce SSO" hint="Block password-based logins for non-admins."><Toggle on={true} onChange={() => {}} label="Enforced"/></SettingRow>
    </div>
  );
}

function AuditPanel() {
  const events = [
    { t: "2 min ago",  who: "Maya Lindqvist", action: "promoted Quote Copilot to prod" },
    { t: "14 min ago", who: "Stoda runtime",  action: "held deploy: drift detected (per-app key rule)" },
    { t: "1 hr ago",   who: "Priya Rangarajan", action: "added rule: Apps with >3 DAU require automated QA" },
    { t: "3 hr ago",   who: "Rohan Patel",    action: "increased budget for Forecast Studio · $4,000/mo" },
    { t: "Yesterday",  who: "Sam Jefferson",  action: "rotated shared OPENAI_API_KEY into per-app keys" },
  ];
  return (
    <div className="card flush">
      <PanelHeader title="Audit log" subtitle="Every workspace event, signed and retained per your retention policy."
        status={<button style={{ padding: "5px 10px", background: "var(--paper)", border: "1px solid var(--tan-2)", color: "var(--ink)", borderRadius: 6, fontSize: 11.5, cursor: "pointer" }}>Export CSV</button>}/>
      <div style={{ borderTop: "1px solid var(--tan-2)" }}>
        {events.map((e, i) => (
          <div key={i} style={{ padding: "12px 20px", borderBottom: i < events.length - 1 ? "1px solid var(--tan-2)" : "none", display: "flex", gap: 14 }}>
            <div style={{ fontSize: 11.5, color: "var(--muted)", minWidth: 90, fontFamily: "var(--mono)" }}>{e.t}</div>
            <div style={{ flex: 1, fontSize: 12.5, color: "var(--ink)" }}><b style={{ fontWeight: 500 }}>{e.who}</b> {e.action}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function TokensPanel() {
  const tokens = [
    { name: "ci-deploy",   created: "Jan 12, 2026", lastUsed: "2 min ago", scope: "deploy" },
    { name: "evidence-export", created: "Mar 04, 2026", lastUsed: "Today",    scope: "read-only" },
  ];
  return (
    <div className="card flush">
      <PanelHeader title="API tokens" subtitle="Programmatic access for CI, exports, and your own automation."
        status={<button style={{ padding: "7px 14px", background: "var(--ink-2)", color: "#fff", border: "none", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer" }}>+ New token</button>}/>
      <table className="t" style={{ borderTop: "1px solid var(--tan-2)" }}>
        <thead><tr><th>Name</th><th>Scope</th><th>Created</th><th>Last used</th><th></th></tr></thead>
        <tbody>
          {tokens.map(t => (
            <tr key={t.name}>
              <td style={{ fontFamily: "var(--mono)", fontSize: 12.5, color: "var(--ink)" }}>{t.name}</td>
              <td><span style={{ fontSize: 11.5, padding: "2px 8px", background: "var(--cream-3)", color: "var(--ink)", borderRadius: 4, fontFamily: "var(--mono)" }}>{t.scope}</span></td>
              <td style={{ fontSize: 12, color: "var(--muted)" }}>{t.created}</td>
              <td style={{ fontSize: 12, color: "var(--muted)" }}>{t.lastUsed}</td>
              <td style={{ textAlign: "right" }}><button style={{ padding: "4px 8px", background: "transparent", border: "1px solid var(--tan-2)", color: "var(--muted)", borderRadius: 6, fontSize: 11.5, cursor: "pointer" }}>Revoke</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { SettingsPage });

// ---------- Operator-only panels ----------
function ProfilePanel() {
  const me = DATA.ME_OPERATOR;
  return (
    <div className="card flush">
      <PanelHeader title="Profile" subtitle="How you appear to the rest of the workspace."/>
      <SettingRow label="Display name">
        <TextField value={me.name} onChange={() => {}}/>
      </SettingRow>
      <SettingRow label="Email" hint="Used for approval requests and audit signing.">
        <code style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink)", padding: "6px 10px", background: "var(--cream-2)", border: "1px solid var(--tan-2)", borderRadius: 6 }}>{me.id === "ml" ? "maya@meridia.co" : "operator@meridia.co"}</code>
      </SettingRow>
      <SettingRow label="Team" hint="Set by your admin via SCIM.">
        <span style={{ fontSize: 13, color: "var(--ink)" }}>{me.team}</span>
      </SettingRow>
    </div>
  );
}

function PersonalNotificationsPanel() {
  const [routes, setRoutes] = useStateS([
    { id: 1, event: "My deploy held",                channel: "DM",          on: true  },
    { id: 2, event: "My test fails",                 channel: "DM",          on: true  },
    { id: 3, event: "My app hits its budget (80%)",  channel: "DM",          on: true  },
    { id: 4, event: "My app hits its budget (100%)", channel: "DM",          on: true  },
    { id: 5, event: "Approval I requested resolves", channel: "DM",          on: true  },
    { id: 6, event: "New outbound from my apps",     channel: "#stoda-revops", on: false },
    { id: 7, event: "Daily digest of my apps",       channel: "DM",          on: false },
  ]);
  const channels = ["DM", "#stoda-revops", "#quote-copilot", "#onboarding", "Email"];

  return (
    <div className="card flush">
      <PanelHeader
        title="Notifications"
        subtitle="Where Stoda pings you. Only events on your apps — your CTO sets fleet-wide rules."
        status={<StatusChip kind="ok">Slack DM as @maya</StatusChip>}/>

      <div style={{ borderTop: "1px solid var(--tan-2)", padding: "18px 20px" }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>Events on my apps</div>
        <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4, marginBottom: 14 }}>Two apps owned: Quote Copilot, Onboarding Wizard.</div>
        <table className="t" style={{ background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 8, overflow: "hidden" }}>
          <thead><tr><th>Event</th><th>Where</th><th style={{ width: 60 }}>On</th></tr></thead>
          <tbody>
            {routes.map(r => (
              <tr key={r.id} style={{ opacity: r.on ? 1 : 0.55 }}>
                <td style={{ fontSize: 12.5, color: "var(--ink)", fontWeight: 500 }}>{r.event}</td>
                <td>
                  <select value={r.channel} onChange={(e) => setRoutes(prev => prev.map(x => x.id === r.id ? { ...x, channel: e.target.value } : x))}
                    style={{ padding: "5px 8px", background: "var(--paper)", border: "1px solid var(--tan-2)", borderRadius: 6, fontSize: 12, fontFamily: "var(--mono)", color: "var(--ink)" }}>
                    {channels.map(c => <option key={c}>{c}</option>)}
                  </select>
                </td>
                <td><Toggle on={r.on} onChange={(v) => setRoutes(prev => prev.map(x => x.id === r.id ? { ...x, on: v } : x))}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <SettingRow label="Quiet hours" hint="Suppress non-urgent pings outside business hours.">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Toggle on={true} onChange={() => {}}/>
          <span style={{ fontSize: 12, color: "var(--muted)" }}>9:00 PM – 7:00 AM, your local time</span>
        </div>
      </SettingRow>

      <SettingRow label="Test ping" hint="Send a sample to confirm routing works.">
        <button style={{ padding: "7px 14px", background: "var(--paper)", border: "1px solid var(--tan-2)", color: "var(--ink)", borderRadius: 6, fontSize: 12.5, cursor: "pointer" }}>Send test DM</button>
      </SettingRow>
    </div>
  );
}

function PersonalTokensPanel() {
  const tokens = [
    { name: "maya-local-cli", created: "Feb 22, 2026", lastUsed: "1h ago", scope: "deploy:my-apps" },
  ];
  return (
    <div className="card flush">
      <PanelHeader title="Personal tokens" subtitle="Tokens scoped to apps you own. Use these from your CLI or local scripts."
        status={<button style={{ padding: "7px 14px", background: "var(--ink-2)", color: "#fff", border: "none", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer" }}>+ New token</button>}/>
      <table className="t" style={{ borderTop: "1px solid var(--tan-2)" }}>
        <thead><tr><th>Name</th><th>Scope</th><th>Created</th><th>Last used</th><th></th></tr></thead>
        <tbody>
          {tokens.map(t => (
            <tr key={t.name}>
              <td style={{ fontFamily: "var(--mono)", fontSize: 12.5, color: "var(--ink)" }}>{t.name}</td>
              <td><span style={{ fontSize: 11.5, padding: "2px 8px", background: "var(--cream-3)", color: "var(--ink)", borderRadius: 4, fontFamily: "var(--mono)" }}>{t.scope}</span></td>
              <td style={{ fontSize: 12, color: "var(--muted)" }}>{t.created}</td>
              <td style={{ fontSize: 12, color: "var(--muted)" }}>{t.lastUsed}</td>
              <td style={{ textAlign: "right" }}><button style={{ padding: "4px 8px", background: "transparent", border: "1px solid var(--tan-2)", color: "var(--muted)", borderRadius: 6, fontSize: 11.5, cursor: "pointer" }}>Revoke</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
