/* ===========================================================================
   launch-settings.jsx — comprehensive "manage the command center" surface.
   Eight tabs of real, editable configuration. Everything writes through the
   mock-db fold seam (launchSettings, launchAccess, launchEngines, ticketPhases,
   timeline) and persists. Registers window.LCC_PAGES.settings.
   =========================================================================== */
const { LccPage: SPage, LccTabs: STabs, LCC_TABS: STABS, Section: SSection,
        Avatar: SAvatar, Bar: SBar, lccInput: sInput, LccField: SField,
        act: sAct, LCC_ACCENTS: SACC, ENGINE_COLORS: SEC } = window;

/* small reusable pill toggle */
function SToggle({ on, onClick }) {
  return (
    <button onClick={onClick} className="pill" style={{ background: on ? "var(--role-accent)" : "transparent", color: on ? "#fff" : "var(--pvt-muted)", borderColor: on ? "var(--role-accent)" : "var(--pvt-border-light)", minWidth: 56, justifyContent: "center" }}>{on ? "On" : "Off"}</button>
  );
}
function SRow({ label, sub, children }) {
  return (
    <div className="stat-row" style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 14, alignItems: "center" }}>
      <div style={{ minWidth: 0 }}><div style={{ fontSize: 13, color: "var(--pvt-text)" }}>{label}</div>{sub && <div style={{ fontSize: 11, color: "var(--pvt-text-dim)", marginTop: 2 }}>{sub}</div>}</div>
      {children}
    </div>
  );
}

/* Searchable owner assignment — click to open a popover, filter the team
   roster by name OR role, pick to assign. Reuses the team roster + Avatar. */
function OwnerPicker({ value, team, onChange }) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState("");
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", onDoc); document.removeEventListener("keydown", onKey); };
  }, [open]);
  const current = team.find((m) => m.name.split(" ")[0] === value);
  const filtered = team.filter((m) => (m.name + " " + m.role).toLowerCase().includes(q.trim().toLowerCase()));
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => { setOpen((o) => !o); setQ(""); }} style={{ ...sInput(), padding: "6px 10px", display: "flex", alignItems: "center", gap: 9, cursor: "pointer", textAlign: "left" }}>
        {current ? <SAvatar name={current.name} color={current.color} size={24} /> : <span style={{ width: 24, height: 24, borderRadius: "50%", border: "1.5px dashed var(--pvt-border-light)", flexShrink: 0 }} />}
        <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          <span style={{ fontSize: 13, color: current ? "var(--pvt-text)" : "var(--pvt-text-dim)" }}>{current ? current.name : (value || "Unassigned")}</span>
          {current && <span style={{ fontSize: 11, color: "var(--pvt-text-dim)", marginLeft: 7 }}>{current.role}</span>}
        </span>
        <span style={{ color: "var(--pvt-text-dim)", fontSize: 10, flexShrink: 0 }}>▾</span>
      </button>
      {open && (
        <div style={{ position: "absolute", top: "calc(100% + 6px)", left: 0, minWidth: "max(100%, 260px)", background: "var(--pvt-surface-raised)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", boxShadow: "0 24px 60px rgba(0,0,0,0.5)", zIndex: 200, overflow: "hidden" }}>
          <div style={{ padding: 8, borderBottom: "1px solid var(--pvt-border-light)" }}>
            <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search name or role…" style={{ ...sInput(), padding: "8px 11px" }} />
          </div>
          <div style={{ maxHeight: 256, overflowY: "auto", padding: 4 }}>
            {filtered.map((m) => {
              const on = m.name.split(" ")[0] === value;
              return (
                <button key={m.id} onClick={() => { onChange(m.name.split(" ")[0]); setOpen(false); }}
                  style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "8px 10px", background: on ? "var(--pvt-surface-mid)" : "transparent", border: 0, borderRadius: "var(--r-sm)", cursor: "pointer", textAlign: "left", color: "var(--pvt-text)", fontFamily: "var(--pvt-font-body)" }}
                  onMouseEnter={(e) => e.currentTarget.style.background = "var(--pvt-surface-mid)"}
                  onMouseLeave={(e) => e.currentTarget.style.background = on ? "var(--pvt-surface-mid)" : "transparent"}>
                  <SAvatar name={m.name} color={m.color} size={30} />
                  <span style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ display: "block", fontSize: 13, fontFamily: "var(--pvt-font-display)" }}>{m.name}</span>
                    <span style={{ display: "block", fontSize: 11, color: "var(--pvt-text-dim)" }}>{m.role}</span>
                  </span>
                  {on && <span style={{ color: "var(--role-accent-bright)", fontSize: 14, flexShrink: 0 }}>✓</span>}
                </button>
              );
            })}
            {filtered.length === 0 && <div style={{ padding: 18, textAlign: "center", fontSize: 12, color: "var(--pvt-text-dim)" }}>No teammate matches “{q}”.</div>}
          </div>
        </div>
      )}
    </div>
  );
}

/* Small reorder control — up/down, reused by phases, timeline, stages. */
function MoveBtns({ i, n, onMove }) {
  const btn = { width: 24, height: 17, display: "grid", placeItems: "center", background: "var(--pvt-surface-light)", border: "1px solid var(--pvt-border-light)", borderRadius: 5, color: "var(--pvt-text-dim)", fontSize: 8, lineHeight: 1, padding: 0, fontFamily: "var(--pvt-font-body)" };
  return (
    <span style={{ display: "inline-flex", flexDirection: "column", gap: 2 }}>
      <button title="Move up" disabled={i === 0} onClick={() => onMove(i, -1)} style={{ ...btn, opacity: i === 0 ? 0.3 : 1, cursor: i === 0 ? "default" : "pointer" }}>▲</button>
      <button title="Move down" disabled={i === n - 1} onClick={() => onMove(i, 1)} style={{ ...btn, opacity: i === n - 1 ? 0.3 : 1, cursor: i === n - 1 ? "default" : "pointer" }}>▼</button>
    </span>
  );
}
/* generic immutable swap */
function swap(arr, i, dir) { const j = i + dir; if (j < 0 || j >= arr.length) return arr; const c = arr.slice(); const t = c[i]; c[i] = c[j]; c[j] = t; return c; }
/* tiny round delete button */
function delBtnStyle() { return { width: 28, height: 28, borderRadius: 8, display: "grid", placeItems: "center", background: "var(--pvt-surface-light)", border: "1px solid var(--pvt-border-light)", color: "var(--pvt-text-dim)", cursor: "pointer", fontSize: 16, lineHeight: 1, flexShrink: 0 }; }

function LccSettings({ tab, go }) {
  const [s, setS] = window.useDB("launchSettings");
  const [access, setAccess] = window.useDB("launchAccess");
  const [engines, setEngines] = window.useDB("launchEngines");
  const [phases, setPhases] = window.useDB("ticketPhases");
  const [timeline, setTimeline] = window.useDB("timeline");
  const DESTS = window.LCC_NAV || [];

  const setFest = (k, v) => setS((x) => ({ ...x, festival: { ...x.festival, [k]: v } }));
  const setStage = (i, v) => setS((x) => ({ ...x, festival: { ...x.festival, stageNames: x.festival.stageNames.map((n, j) => j === i ? v : n) } }));
  const setBrand = (k, v) => setS((x) => ({ ...x, branding: { ...x.branding, [k]: v } }));
  const toggleChan = (k) => setS((x) => ({ ...x, alerting: { ...x.alerting, channels: { ...x.alerting.channels, [k]: !x.alerting.channels[k] } } }));
  const toggleEvent = (k) => setS((x) => ({ ...x, alerting: { ...x.alerting, events: { ...x.alerting.events, [k]: !x.alerting.events[k] } } }));
  const setEsc = (k, v) => setS((x) => ({ ...x, alerting: { ...x.alerting, escalation: { ...x.alerting.escalation, [k]: v } } }));

  // ----- invites / roles -----
  const [invEmail, setInvEmail] = React.useState("");
  const [invRole, setInvRole] = React.useState("Editor");
  const sendInvite = () => {
    if (!invEmail.trim()) return;
    setAccess((a) => ({ ...a, invites: [...(a.invites || []), { id: "inv" + Date.now(), email: invEmail.trim(), role: invRole, status: "pending", sent: "now" }] }));
    if (window.argtPing) window.argtPing("Invite sent to " + invEmail.trim());
    setInvEmail("");
  };
  const setPersonAccess = (id, val) => setS((x) => ({ ...x, roles: x.roles.map((r) => r.id === id ? { ...r, access: val } : r) }));

  // ----- role & permission editor (launchAccess.roles + access matrix) -----
  const [newRole, setNewRole] = React.useState("");
  const addRole = () => {
    const name = newRole.trim();
    if (!name || access.roles.includes(name)) return;
    setAccess((a) => ({ ...a, roles: [...a.roles, name], access: { ...a.access, [name]: ["today"] } }));
    if (window.argtPing) window.argtPing("Role “" + name + "” added");
    setNewRole("");
  };
  const removeRole = (r) => setAccess((a) => {
    const acc = { ...a.access }; delete acc[r];
    return { ...a, roles: a.roles.filter((x) => x !== r), access: acc, currentRole: a.currentRole === r ? "Owner" : a.currentRole };
  });
  const toggleDest = (r, d) => setAccess((a) => {
    const cur = a.access[r] || [];
    return { ...a, access: { ...a.access, [r]: cur.includes(d) ? cur.filter((x) => x !== d) : [...cur, d] } };
  });

  // ----- ticket phase editor -----
  const setPhase = (id, k, v) => setPhases((xs) => xs.map((p) => p.id === id ? { ...p, [k]: v } : p));
  const movePhase = (i, dir) => setPhases((xs) => swap(xs, i, dir));
  const removePhase = (id) => setPhases((xs) => xs.filter((p) => p.id !== id));
  const addPhase = () => { setPhases((xs) => [...xs, { id: "tp" + Date.now(), phase: "New phase", status: "pending", sold: 0, allocation: 1000, goLive: "TBD", price: "$0" }]); if (window.argtPing) window.argtPing("Phase added"); };

  // ----- production timeline editor -----
  const setWeek = (i, k, v) => setTimeline((xs) => xs.map((w, j) => j === i ? { ...w, [k]: v } : w));
  const moveWeek = (i, dir) => setTimeline((xs) => swap(xs, i, dir));
  const removeWeek = (i) => setTimeline((xs) => xs.filter((_, j) => j !== i));
  const addWeek = () => { setTimeline((xs) => [...xs, { week: "T-0", label: "New milestone block", engine: "content", status: "todo", milestones: [] }]); if (window.argtPing) window.argtPing("Timeline block added"); };

  // ----- festival stage editor -----
  const moveStage = (i, dir) => setS((x) => ({ ...x, festival: { ...x.festival, stageNames: swap(x.festival.stageNames, i, dir) } }));
  const removeStage = (i) => setS((x) => ({ ...x, festival: { ...x.festival, stageNames: x.festival.stageNames.filter((_, j) => j !== i) } }));
  const addStage = () => setS((x) => ({ ...x, festival: { ...x.festival, stageNames: [...x.festival.stageNames, "New stage"] } }));

  const F = s.festival, B = s.branding, A = s.alerting, ST = s.storage;
  const team = window.ARGT_DB.get("launchTeam") || [];
  const RET = { "180 days": 180, "365 days": 365, "3 years": 1095, "Forever": 0 };
  const retLabel = (d) => Object.keys(RET).find((k) => RET[k] === d) || "365 days";
  const records = ["launchTasks", "pipelineItems", "incidents", "commsCalendar", "contentStudio", "checklists", "launchFiles", "budgetInvoices"].reduce((n, k) => n + ((window.ARGT_DB.get(k) || []).length), 0);

  return (
    <SPage eyebrow="SETTINGS" title="Configuration"
      lede="Everything that defines the launch: festival profile and dates, the timeline and ticket-phase cascade, engine ownership, who has access, integrations, alerting, branding, and storage and data. Changes save and persist."
      actions={<button className="pill active" onClick={sAct("All settings saved")}>Save changes</button>}>
      <STabs tabs={STABS.settings} active={tab} onChange={(t) => go("settings", t)} />

      {/* ---------------- FESTIVAL ---------------- */}
      {tab === "festival" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <SSection title="Festival profile">
            <div className="grid-form-2">
              <SField label="Festival name"><input style={sInput()} value={F.name} onChange={(e) => setFest("name", e.target.value)} /></SField>
              <SField label="Presented by"><input style={sInput()} value={F.presentedBy} onChange={(e) => setFest("presentedBy", e.target.value)} /></SField>
              <div style={{ gridColumn: "1 / -1" }}><SField label="Tagline"><input style={sInput()} value={F.tagline} onChange={(e) => setFest("tagline", e.target.value)} /></SField></div>
              <SField label="Venue"><input style={sInput()} value={F.venue} onChange={(e) => setFest("venue", e.target.value)} /></SField>
              <SField label="Location"><input style={sInput()} value={F.address} onChange={(e) => setFest("address", e.target.value)} /></SField>
            </div>
          </SSection>
          <SSection title="Dates & scale">
            <div className="grid-form-2">
              <SField label="Gates open"><input type="date" style={sInput()} value={F.startDate} onChange={(e) => setFest("startDate", e.target.value)} /></SField>
              <SField label="Gates close"><input type="date" style={sInput()} value={F.endDate} onChange={(e) => setFest("endDate", e.target.value)} /></SField>
              <SField label="Daily doors"><input type="time" style={sInput()} value={F.gatesOpen} onChange={(e) => setFest("gatesOpen", e.target.value)} /></SField>
              <SField label="Capacity"><input style={sInput()} value={F.capacity} onChange={(e) => setFest("capacity", e.target.value)} /></SField>
              <SField label="Artists"><input style={sInput()} value={F.artists} onChange={(e) => setFest("artists", e.target.value)} /></SField>
              <SField label="Beneficiary pledge"><div style={{ display: "flex", gap: 8 }}><input style={{ ...sInput(), width: 70 }} value={F.pledgePct} onChange={(e) => setFest("pledgePct", e.target.value)} /><input style={sInput()} value={F.beneficiary} onChange={(e) => setFest("beneficiary", e.target.value)} /></div></SField>
            </div>
          </SSection>
          <SSection title="Stages" action={<button className="pill active" onClick={addStage}>Add stage</button>}>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {F.stageNames.map((n, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 28px 1fr auto", gap: 10, alignItems: "center" }}>
                  <MoveBtns i={i} n={F.stageNames.length} onMove={moveStage} />
                  <span style={{ width: 28, height: 28, borderRadius: 7, background: "var(--pvt-surface-light)", display: "grid", placeItems: "center", fontSize: 12, color: "var(--pvt-text-dim)", flexShrink: 0 }}>{i + 1}</span>
                  <input style={sInput()} value={n} onChange={(e) => setStage(i, e.target.value)} />
                  <button title="Remove stage" onClick={() => removeStage(i)} style={delBtnStyle()}>×</button>
                </div>
              ))}
              {F.stageNames.length === 0 && <div style={{ padding: 16, textAlign: "center", fontSize: 12, color: "var(--pvt-text-dim)" }}>No stages yet. Add one above.</div>}
            </div>
          </SSection>
        </div>
      )}

      {/* ---------------- TIMELINE & PHASES ---------------- */}
      {tab === "timeline" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <SSection title="Ticket phase cascade" action={<button className="pill active" onClick={addPhase}>Add phase</button>}>
            <div style={{ display: "grid", gridTemplateColumns: "auto 1.2fr 0.9fr 0.9fr 0.9fr 0.8fr auto", gap: 10, padding: "0 4px 10px", fontSize: 10, fontWeight: 800, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--pvt-text-dim)", borderBottom: "1px solid var(--pvt-border-light)" }}>
              <span>Order</span><span>Phase</span><span>Status</span><span>Go-live</span><span>Allocation</span><span>Price</span><span></span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 8 }}>
              {phases.map((p, i) => (
                <div key={p.id} style={{ display: "grid", gridTemplateColumns: "auto 1.2fr 0.9fr 0.9fr 0.9fr 0.8fr auto", gap: 10, alignItems: "center", padding: "4px 4px" }}>
                  <MoveBtns i={i} n={phases.length} onMove={movePhase} />
                  <input style={{ ...sInput(), padding: "8px 10px" }} value={p.phase} onChange={(e) => setPhase(p.id, "phase", e.target.value)} />
                  <select style={{ ...sInput(), padding: "8px 10px" }} value={p.status} onChange={(e) => setPhase(p.id, "status", e.target.value)}><option value="pending">Pending</option><option value="ready">Ready</option><option value="live">Live</option></select>
                  <input style={{ ...sInput(), padding: "8px 10px" }} value={p.goLive} onChange={(e) => setPhase(p.id, "goLive", e.target.value)} />
                  <input style={{ ...sInput(), padding: "8px 10px" }} value={p.allocation} onChange={(e) => setPhase(p.id, "allocation", +e.target.value || 0)} />
                  <input style={{ ...sInput(), padding: "8px 10px" }} value={p.price} onChange={(e) => setPhase(p.id, "price", e.target.value)} />
                  <button title="Remove phase" onClick={() => removePhase(p.id)} style={delBtnStyle()}>×</button>
                </div>
              ))}
              {phases.length === 0 && <div style={{ padding: 16, textAlign: "center", fontSize: 12, color: "var(--pvt-text-dim)" }}>No phases. Add the first one above.</div>}
            </div>
          </SSection>
          <SSection title="Production timeline" action={<button className="pill active" onClick={addWeek}>Add block</button>}>
            <SRow label="Timeline length" sub="Weeks of build before gates"><input style={{ ...sInput(), width: 90 }} value={s.timelineWeeks ?? 20} onChange={(e) => setS((x) => ({ ...x, timelineWeeks: e.target.value }))} /></SRow>
            <div style={{ height: 12 }} />
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {timeline.map((w, i) => (
                <div key={i} style={{ background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", padding: "12px 14px", display: "flex", flexDirection: "column", gap: 10 }}>
                  <div style={{ display: "grid", gridTemplateColumns: "auto 90px 1fr 1fr auto", gap: 10, alignItems: "center" }}>
                    <MoveBtns i={i} n={timeline.length} onMove={moveWeek} />
                    <input style={{ ...sInput(), padding: "8px 10px", fontFamily: "var(--pvt-font-display)", color: "var(--role-accent-bright)" }} value={w.week} onChange={(e) => setWeek(i, "week", e.target.value)} />
                    <select style={{ ...sInput(), padding: "8px 10px" }} value={w.engine} onChange={(e) => setWeek(i, "engine", e.target.value)}>{Object.keys(window.ENGINE_LABELS).map((k) => <option key={k} value={k}>{window.ENGINE_LABELS[k]}</option>)}</select>
                    <select style={{ ...sInput(), padding: "8px 10px" }} value={w.status} onChange={(e) => setWeek(i, "status", e.target.value)}><option value="todo">To do</option><option value="doing">In progress</option><option value="done">Done</option></select>
                    <button title="Remove block" onClick={() => removeWeek(i)} style={delBtnStyle()}>×</button>
                  </div>
                  <input style={{ ...sInput(), padding: "9px 11px" }} placeholder="Milestone block label" value={w.label} onChange={(e) => setWeek(i, "label", e.target.value)} />
                  <label style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                    <span style={{ fontSize: 10, color: "var(--pvt-text-dim)", textTransform: "uppercase", letterSpacing: "0.07em", fontWeight: 700 }}>Milestones (comma-separated)</span>
                    <input style={{ ...sInput(), padding: "9px 11px" }} placeholder="e.g. Headliners signed, Phase 1 on-sale" value={(w.milestones || []).join(", ")} onChange={(e) => setWeek(i, "milestones", e.target.value.split(",").map((m) => m.trim()).filter(Boolean))} />
                  </label>
                </div>
              ))}
              {timeline.length === 0 && <div style={{ padding: 16, textAlign: "center", fontSize: 12, color: "var(--pvt-text-dim)" }}>No timeline blocks. Add the first one above.</div>}
            </div>
          </SSection>
        </div>
      )}

      {/* ---------------- ENGINES ---------------- */}
      {tab === "engines" && (
        <SSection title="Engine configuration" action={<span className="micro">{engines.filter((e) => e.enabled).length}/{engines.length} ENABLED</span>}>
          <div style={{ display: "grid", gridTemplateColumns: "160px 1fr 1fr auto", gap: 10, padding: "0 4px 10px", fontSize: 10, fontWeight: 800, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--pvt-text-dim)", borderBottom: "1px solid var(--pvt-border-light)" }}>
            <span>Engine</span><span>Owner</span><span>Target</span><span>Enabled</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 8 }}>
            {engines.map((e) => (
              <div key={e.key} style={{ display: "grid", gridTemplateColumns: "160px 1fr 1fr auto", gap: 10, alignItems: "center", padding: "6px 4px", opacity: e.enabled ? 1 : 0.55 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "var(--pvt-font-display)", fontSize: 14 }}><span style={{ width: 9, height: 9, borderRadius: "50%", background: SEC[e.key] }} />{e.label}</span>
                <OwnerPicker value={e.owner} team={team} onChange={(v) => setEngines((xs) => xs.map((x) => x.key === e.key ? { ...x, owner: v } : x))} />
                <input style={{ ...sInput(), padding: "8px 10px" }} value={e.target} onChange={(ev) => setEngines((xs) => xs.map((x) => x.key === e.key ? { ...x, target: ev.target.value } : x))} />
                <SToggle on={e.enabled} onClick={() => setEngines((xs) => xs.map((x) => x.key === e.key ? { ...x, enabled: !x.enabled, status: !x.enabled ? "attention" : "paused" } : x))} />
              </div>
            ))}
          </div>
        </SSection>
      )}

      {/* ---------------- TEAM & ROLES ---------------- */}
      {tab === "roles" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <SSection title="Roles & permissions" action={<span className="micro">{access.roles.length} ROLES</span>}>
            <p style={{ fontSize: 11.5, color: "var(--pvt-text-dim)", margin: "0 0 14px", lineHeight: 1.5 }}>Define each role and exactly which destinations it can open. Owner always keeps full access. The role you’re viewing as is gated live by this matrix.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {access.roles.map((r) => {
                const owner = r === "Owner";
                const acc = owner ? DESTS.map((d) => d.id) : (access.access[r] || []);
                return (
                  <div key={r} style={{ background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", padding: "12px 14px" }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 11 }}>
                      <span style={{ display: "flex", alignItems: "center", gap: 9, fontFamily: "var(--pvt-font-display)", fontSize: 14 }}>
                        {r}
                        {owner && <span className="micro">LOCKED</span>}
                        {r === access.currentRole && <span style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: "0.05em", color: "var(--role-accent-bright)" }}>VIEWING AS</span>}
                      </span>
                      {!owner && <button className="pill" onClick={() => removeRole(r)} style={{ color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }}>Remove</button>}
                    </div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                      {DESTS.map((d) => {
                        const on = acc.includes(d.id);
                        return <button key={d.id} disabled={owner} onClick={() => toggleDest(r, d.id)} className="pill" style={{ background: on ? "var(--role-accent)" : "transparent", color: on ? "#fff" : "var(--pvt-muted)", borderColor: on ? "var(--role-accent)" : "var(--pvt-border-light)", cursor: owner ? "default" : "pointer", opacity: owner && !on ? 0.4 : 1 }}>{d.label}</button>;
                      })}
                    </div>
                  </div>
                );
              })}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, marginTop: 14 }}>
              <input style={sInput()} placeholder="New role name (e.g. Coordinator)" value={newRole} onChange={(e) => setNewRole(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") addRole(); }} />
              <button className="pill active" onClick={addRole}>Add role</button>
            </div>
          </SSection>
          <SSection title="Invite to the command center">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 160px auto", gap: 10, alignItems: "center" }}>
              <input style={sInput()} placeholder="name@argt.com" value={invEmail} onChange={(e) => setInvEmail(e.target.value)} />
              <select style={sInput()} value={invRole} onChange={(e) => setInvRole(e.target.value)}><option>Admin</option><option>Editor</option><option>Viewer</option></select>
              <button className="pill active" onClick={sendInvite}>Send invite</button>
            </div>
            <p style={{ fontSize: 11.5, color: "var(--pvt-text-dim)", margin: "12px 0 0", lineHeight: 1.5 }}>Admins can open Settings and edit the festival profile. Editors work the operational hubs. Viewers are read-only. Only Owner and Admin can reach this configuration surface.</p>
          </SSection>
          <SSection title="Team & access">
            <div className="stat-rows">
              {s.roles.map((r) => (
                <div key={r.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "auto 1fr 1fr 130px", gap: 14, alignItems: "center" }}>
                  <SAvatar name={r.name} size={28} />
                  <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13.5 }}>{r.name}</span>
                  <span style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}>{r.scope}</span>
                  {r.access === "Owner" ? <Badge kind="approved">Owner</Badge> : (
                    <select style={{ ...sInput(), padding: "7px 10px", fontSize: 12 }} value={r.access} onChange={(e) => setPersonAccess(r.id, e.target.value)}>
                      {Array.from(new Set([...access.roles.filter((x) => x !== "Owner"), r.access])).map((opt) => <option key={opt} value={opt}>{opt}</option>)}
                    </select>
                  )}
                </div>
              ))}
            </div>
          </SSection>
          {(access.invites || []).length > 0 && (
            <SSection title="Pending invites" action={<span className="micro">{access.invites.length} OUTSTANDING</span>}>
              <div className="stat-rows">
                {access.invites.map((iv) => (
                  <div key={iv.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "1fr auto auto auto", gap: 14, alignItems: "center" }}>
                    <span style={{ fontSize: 13 }}>{iv.email}</span>
                    <Badge kind="review">{iv.role}</Badge>
                    <span style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>sent {iv.sent}</span>
                    <button className="pill" onClick={() => setAccess((a) => ({ ...a, invites: a.invites.filter((x) => x.id !== iv.id) }))}>Revoke</button>
                  </div>
                ))}
              </div>
            </SSection>
          )}
        </div>
      )}

      {/* ---------------- INTEGRATIONS ---------------- */}
      {tab === "integrations" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {window.PMIntegrations ? <window.PMIntegrations /> : null}
          <SSection title="Connected services">
          <div className="stat-rows">
            {s.integrations.map((ig) => {
              const on = ig.status === "connected";
              return (
                <div key={ig.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "150px 1fr auto", gap: 14, alignItems: "center" }}>
                  <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13.5 }}>{ig.name}</span>
                  <div style={{ minWidth: 0 }}><div style={{ fontSize: 12.5, color: "var(--pvt-muted)" }}>{ig.purpose}</div><div style={{ fontSize: 11, color: ig.status === "action" ? "#E0B638" : "var(--pvt-text-dim)" }}>{ig.detail}</div></div>
                  <button className="pill" style={on ? { background: "var(--role-accent)", color: "#fff", borderColor: "var(--role-accent)" } : {}} onClick={() => setS((x) => ({ ...x, integrations: x.integrations.map((q) => q.id === ig.id ? { ...q, status: on ? "off" : "connected", detail: on ? "Not connected" : "Connected just now" } : q) }))}>{on ? "Connected" : ig.status === "action" ? "Reauthorize" : "Connect"}</button>
                </div>
              );
            })}
          </div>
        </SSection>
        </div>
      )}

      {/* ---------------- ALERTS ---------------- */}
      {tab === "alerts" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <SSection title="Channels">
            <div className="stat-rows">{Object.entries(A.channels).map(([k, v]) => <SRow key={k} label={k}><SToggle on={v} onClick={() => toggleChan(k)} /></SRow>)}</div>
          </SSection>
          <SSection title="Notify me when">
            <div className="stat-rows">{Object.entries(A.events).map(([k, v]) => <SRow key={k} label={k}><SToggle on={v} onClick={() => toggleEvent(k)} /></SRow>)}</div>
          </SSection>
          <SSection title="Incident escalation">
            <div className="stat-rows">
              {Object.entries(A.escalation).map(([k, v]) => (
                <SRow key={k} label={k} sub={k === "P1" ? "Critical" : k === "P2" ? "Major" : "Minor"}>
                  <select style={{ ...sInput(), padding: "7px 10px", fontSize: 12, width: 150 }} value={v} onChange={(e) => setEsc(k, e.target.value)}><option>Call + SMS</option><option>SMS</option><option>Slack</option><option>In-app</option></select>
                </SRow>
              ))}
              <SRow label="Daily digest" sub="Sent every morning"><input type="time" style={{ ...sInput(), width: 130 }} value={A.digestTime === "8:00 AM" ? "08:00" : A.digestTime} onChange={(e) => setS((x) => ({ ...x, alerting: { ...x.alerting, digestTime: e.target.value } }))} /></SRow>
            </div>
          </SSection>
        </div>
      )}

      {/* ---------------- BRANDING ---------------- */}
      {tab === "branding" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <SSection title="Accent color">
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              {Object.keys(SACC).map((k) => (
                <button key={k} onClick={() => setBrand("accent", k)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 16px", borderRadius: "var(--r-md)", background: B.accent === k ? "var(--pvt-surface-light)" : "var(--pvt-surface-mid)", border: "1px solid " + (B.accent === k ? SACC[k].bright : "var(--pvt-border-light)"), cursor: "pointer", color: "var(--pvt-text)" }}>
                  <span style={{ width: 22, height: 22, borderRadius: "50%", background: SACC[k].bright }} /><span style={{ fontSize: 13, textTransform: "capitalize" }}>{k}</span>
                </button>
              ))}
            </div>
          </SSection>
          <SSection title="Theme & logo">
            <div className="grid-form-2">
              <SField label="Theme"><select style={sInput()} value={B.theme} onChange={(e) => setBrand("theme", e.target.value)}><option>Obsidian</option><option>Midnight</option><option>Ink</option></select></SField>
              <SField label="Logo"><button className="pill" style={{ width: "100%", justifyContent: "center", border: "1.5px dashed var(--pvt-border-light)", padding: "11px" }} onClick={sAct("Logo upload opens in the fold")}>Upload logo (SVG or PNG)</button></SField>
            </div>
          </SSection>
        </div>
      )}

      {/* ---------------- PLAN & DATA ---------------- */}
      {tab === "data" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="grid-cols-3">
            <Kpi label="People with access" num={String(s.roles.length)} delta="Team members" glyph="users" />
            <Kpi label="Storage used" num={ST.usedGb + " GB"} delta={"of " + ST.totalGb + " GB"} glyph="file" />
            <Kpi label="Records" num={records.toLocaleString()} delta="Across the launch" glyph="chart" />
          </div>
          <SSection title="Storage">
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}><span style={{ color: "var(--pvt-muted)" }}>Used</span><span style={{ fontFamily: "var(--pvt-font-display)" }}>{ST.usedGb} GB of {ST.totalGb} GB</span></div>
              <SBar pct={ST.usedGb / ST.totalGb * 100} />
              <SRow label="Data retention" sub="How long records are kept"><select style={{ ...sInput(), padding: "7px 10px", fontSize: 12, width: 150 }} value={retLabel(ST.retentionDays)} onChange={(e) => setS((x) => ({ ...x, storage: { ...x.storage, retentionDays: RET[e.target.value] } }))}><option>180 days</option><option>365 days</option><option>3 years</option><option>Forever</option></select></SRow>
            </div>
          </SSection>
          <SSection title="Data">
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <button className="pill" onClick={sAct("Exporting all launch data")}>Export all data</button>
              <button className="pill" onClick={sAct("Backup created")}>Create backup</button>
            </div>
          </SSection>
          <SSection title="Danger zone" style={{ borderColor: "rgba(242,91,167,0.3)" }}>
            <p style={{ fontSize: 12.5, color: "var(--pvt-muted)", margin: "0 0 14px", lineHeight: 1.5 }}>Reset the command center back to seed data. This clears every edit, task, incident, and invite you have made in this demo.</p>
            <button className="pill" style={{ color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }} onClick={() => { window.ARGT_DB.reset(); if (window.argtPing) window.argtPing("Command center reset to seed data"); }}>Reset to seed data</button>
          </SSection>
        </div>
      )}
    </SPage>
  );
}

window.LCC_PAGES = Object.assign(window.LCC_PAGES || {}, {
  settings: (tab, go) => <LccSettings tab={tab} go={go} />,
});
